Java Reference
In-Depth Information
2. (a) true
(b) false
(c) true
(d) false
(e) true
(f) false
(g) false
(h) true
(i) true
3. (a) 13 21
(b) 5 6
(c) 6 5
(d) 7 11
4. (a) 10 6
(b) 9 9
(c) 3 4
(d) 29 30
5. Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
int number = console.nextInt();
if (number % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
6. The code incorrectly prints that even numbers not divisible by 3 are odd, because the
else statement matches the most closely nested if statement ( number % 3 == 0) ,
not the outer if statement.
The following change corrects the problem. Note the braces around the outer if
statement:
if (number % 2 == 0) {
if (number % 3 == 0) {
System.out.println("Divisible by 6.");
}
}
else {
System.out.println("Odd.");
}
Search WWH ::




Custom Search