Java Reference
In-Depth Information
if (values.length > 1)
for (int i = 0; i < values.length; i++)
if (values[i] > 0)
sum += values[i];
else // oops!
sum = values[0];
return sum;
}
The else clause looks as if it is bound to the array length check, but that
is a mirage of indentation, and indentation is ignored. Instead, an else
clause is bound to the most recent if that does not have one. Thus, the
previous block of code is equivalent to
public double sumPositive(double[] values) {
double sum = 0.0;
if (values.length > 1)
for (int i = 0; i < values.length; i++)
if (values[i] > 0)
sum += values[i];
else // oops!
sum = values[0];
return sum;
}
This is probably not what was intended. To bind the else clause to the
first if , you can use braces to create blocks:
public double sumPositive(double[] values) {
double sum = 0.0;
if (values.length > 1) {
for (int i = 0; i < values.length; i++)
 
Search WWH ::




Custom Search