ANSWERS TO MORE PRACTICE PROBLEMS // Problem 1. public static void main(String[] args) { String s; char x; s = JOptionPane.showMessageDialog("Enter a string."); x = JOptionPane.showMessageDialog("Enter a letter.").charAt(0); if (s.length() == 0) System.out.println("String is length 0"); else if(s.charAt(0) == x) System.out.println("First letter of string is " + x + "."); else System.out.println("First letter of string is not " + x + "."); } // Problem 2. // To convert a digit char to an int, subtract 48 from its ascii code. public static void main(String[] args) { String s; int i, digit, sum = 0; s = JOptionPane.showMessageDialog("Enter an int."); for(i = 0; i < s.length(); i++) { digit = s.charAt(i) - 48; sum += digit; } System.out.println("The sum of the digits is " + sum + "."); } // Problem 3. public static void main(String[] args) { int number, factor; boolean flag = true; number = JOptionPane.showMessageDialog("Enter a positive int."); for(factor = 2; factor <= number - 1; factor++) if (number % factor == 0) flag = false; if (flag) System.out.println("Prime") else System.out.println("Composite"); } // Problem 4 public static void main(String[] args) { int i, j; VendingMachine vm = new VendingMachine(10); for(j = 1; j <=4; j++) { for(i = 1; i <= 3; i++) vm.depositQuarter(); vm.selectCandy(); } vm.printStatus(); }