Part of one of our assignments was to generate an array and then find the sum, average, lowest, and highest values. I have all of those working, but our teacher has asked us instead to return the index of the highest and lowest values plus one (to coincide with a month number).
The issue I’m running into is that trying to return the index it always returns the highest value.
public double getHighRain() { double high = 0.0; double highIndex = 0.0; for(int index = 1; index < rainFall.length; index++) { if (rainFall[index] > high) high = rainFall[index]; highIndex = index + 1; } //return high; return highIndex; } /** * Method uses enhanced for loop to calculate the lowest amount of rainfall * @return */ public double getLowRain() { double low = rainFall[0]; double lowIndex = 0.0; for(int index = 1; index < rainFall.length; index++) { if (rainFall[index] < low) low = rainFall[index]; lowIndex = index + 1; } //return low; return lowIndex; }
Advertisement
Answer
It appears you’ve essentially typoed.
for (int index = 1; index < rainFall.length; index++) { if (rainFall[index] > high) high = rainFall[index]; highIndex = index + 1; }
Your indentation suggests highIndex = index + 1;
should only be executed if the condition is true, but because you don’t use braces, this condition is executed on every iteration through the loop.
Perhaps you meant to write:
for (int index = 1; index < rainFall.length; index++) { if (rainFall[index] > high) { high = rainFall[index]; highIndex = index + 1; } }
Indentation is very useful to human beings reading your code, but it means nothing to the machine in Java.
You also likely meant to start at the beginning of the array, which is index 0
.
for (int index = 0; index < rainFall.length; index++) { if (rainFall[index] > high) { high = rainFall[index]; highIndex = index + 1; } }