Java Reference
In-Depth Information
19. public static boolean hasPennies(int cents) {
return cents % 5 != 0;
}
20. Method call
Value returned
mystery(3, 3)
3
mystery(5, 3)
1
mystery(2, 6)
2
mystery(12, 18)
6
mystery(30, 75)
15
21. The code will get stuck in an infinite loop when the current date is the end of a leap
year. On December 31 the days value will be 366, so code enters the if
(isLeapYear) statement but does not enter the if (days > 366) statement. So
the loop does not subtract any days and never terminates. The code can be fixed by
adding a break statement to the loop (see Appendix D):
int days = getTotalDaysSince1980();
year = 1980;
while (days > 365) { // subtract out years
if (isLeapYear(year)) {
if (days > 366) {
days -= 366;
year += 1;
} else { //
break; // new code here
} //
} else {
days -= 365;
year += 1;
}
}
22. (a) !b
(b) (x <= y) || (y <= z)
(c) (x != y) && (x > z)
(d) (x % 2 == 0) || !b
(e) (x / 2 != 13) && !b && (z * 3 != 96)
(f) (z >= x) || (z <= y && x < y)
23. The code should reprompt for a valid integer for the user's age and a valid real
number for the user's GPA. If the user types a token of the wrong type, the line of
input should be consumed and the user should be reprompted.
The following code implements the corrected behavior:
Scanner console = new Scanner(System.in);
System.out.print("Type your age: ");
Search WWH ::




Custom Search