Java Reference
In-Depth Information
Invalid values are when a = 0 (because it makes the denominator of the equation
equal 0), or when b 2 - 4 ac < 0, because then it has no real square root.
26. The code fails when more than one number is odd, because it uses else if rather
than if . The tests should not be nested because they are not mutually exclusive;
more than one number could be odd. The following code fixes the problem:
public static void printNumOdd(int n1, int n2, int n3) {
int count = 0;
if (n1 % 2 != 0) {
count++;
}
if (n2 % 2 != 0) {
count++;
}
if (n3 % 2 != 0) {
count++;
}
System.out.println(count +
" of the 3 numbers are odd.");
}
The following version without if statements also works:
public static void printNumOdd(int n1, int n2, int n3) {
int count = n1 % 2 + n2 % 2 + n3 % 2;
System.out.println(count +
" of the 3 numbers are odd.");
}
Chapter 5
1. (a) Executes body 10 times.
Output is
1 11 21 31 41 51 61 71 81 91
(b) Executes body 0 times.
No output.
(c) Loops infinitely.
Output is
250
250
250
...
(d) Executes body 3 times.
Output is
2 4 16
 
Search WWH ::




Custom Search