Java Reference
In-Depth Information
24.
The code fails when
n3
is the smallest of the three numbers; for example, when the
parameters' values are
(4, 7, 2)
, the code should return
4
but instead returns
2
.
The method could be correctly written as follows:
public static int medianOf3(int n1, int n2, int n3) {
if (n1 < n2 && n1 < n3) {
if (n2 < n3) {
return n2;
} else {
return n3;
}
} else if (n2 < n1 && n2 < n3) {
if (n1 < n3) {
return n1;
} else {
return n3;
}
} else { // (n3 < n1 && n3 < n2)
if (n1 < n2) {
return n1;
} else {
return n2;
}
}
}
Alternatively, here is a shorter version:
public static int medianOf3(int n1, int n2, int n3) {
return Math.max(Math.max(Math.min(n1, n2),
Math.min(n2, n3)),
Math.min(n1, n3));
}
25.
// Throws an exception if a, b, c are invalid
public static void quadratic(int a, int b, int c) {
double determinant = b * b - 4 * a * c;
if (a == 0) {
throw new IllegalArgumentException(
"Invalid a value of 0");
}
if (determinant < 0) {
throw new IllegalArgumentException(
"Invalid determinant");
}
...
}
Search WWH ::
Custom Search