Java Reference
In-Depth Information
14. Scanner console = new Scanner(System.in);
System.out.print("How many numbers? ");
int count = console.nextInt();
int product = 1;
for (int i = 1; i <= count; i++) {
System.out.print("Next number --> ");
int num = console.nextInt();
product *= num;
}
System.out.println("Product = " + product);
15. The expression equals 6.800000000000001 because the limited precision of the
double type led to a roundoff error.
16. The expression gpa * 3 equals 9.600000000000001 because of a roundoff
error. To fix this, test that the value is close to 9.6 rather than exactly equal
to it:
double gpa = 3.2;
if (Math.abs(gpa * 3 - 9.6) < 0.1) {
System.out.println("You earned enough credits.");
}
17. efg
nopqrs
qr
18. if (Character.isUpperCase(theString.charAt(0))) {
...
}
19. The toLowerCase method cannot be called on a char value, which is
what the charAt method returns. A better solution would be to call the
Character.toLowerCase method on the characters of the string:
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.toLowerCase(s.charAt(i)) == 'e') {
count++;
}
}
Another solution would be to lowercase the entire string once before the loop:
s = s.toLowerCase();
int count = 0;
for (int i = 0; i < s.length(); i++) {
Search WWH ::




Custom Search