Reputation: 19
been working at a Java problem for a while now. Having some issue with getting the array index that corresponds to the highest value. I'm pretty sure I understand the logic behind doing so, as I successfully retrieved the index that contained the lowest value. This is what I have:
public static void main(String[] args) {
double array[] = {1.12, 2.24, 3.36, 0.48, 2.00, 5.00, 12.12, 1.48, 3.12, 3.24, 6.6, 1.12};
double highestValue = array[0];
int highIndex = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > highestValue)
highIndex = i;
}
System.out.println(highIndex);
}
However, for this array, my code returns an index of 10, which corresponds to 6.6. But the highest value in the array is 12.12 at index 6. Any reasons why I keep getting 10 as the highest index? The code works fine for retrieving the lowest index if I reverse the logic, but I'm not sure what I'm doing wrong here. Thanks for any help.
Upvotes: 1
Views: 333
Reputation: 17474
Because you forgot to update the highest value.
Add this line:
highestValue = array[i];
Change your code to:
if (array[i] > highestValue) {
highIndex = i;
highestValue = array[i]; //Add this line
}
If you do not update the highest value, you are always comparing with the first element in the array.
Proof:
Comparing 1.12 with 1.12
Comparing 2.24 with 1.12
2.24 is higher.
Comparing 3.36 with 1.12
3.36 is higher.
Comparing 0.48 with 1.12
Comparing 2.0 with 1.12
2.0 is higher.
Comparing 5.0 with 1.12
5.0 is higher.
Comparing 12.12 with 1.12
12.12 is higher.
Comparing 1.48 with 1.12
1.48 is higher.
Comparing 3.12 with 1.12
3.12 is higher.
Comparing 3.24 with 1.12
3.24 is higher.
Comparing 6.6 with 1.12
6.6 is higher.
Comparing 1.12 with 1.12
You can do your own testing by adding a few lines of println statements to your codes like this. (Alternative of using debugger)
for (int i = 0; i < array.length; i++) {
System.out.println("Comparing " + array[i] + " with " + highestValue);
if (array[i] > highestValue) {
highIndex = i;
//highestValue = array[i];
System.out.println(array[i] + " is higher.");
}
}
Upvotes: 3
Reputation: 394146
You forgot to update highestValue
. Therefore, each i
for which array[i]
is higher than array[0]
causes the highIndex
to be updated. 10 is the last such index.
Your code should look like this :
for (int i = 0; i < array.length; i++) {
if (array[i] > highestValue) {
highIndex = i;
highestValue = array[i];
}
}
Upvotes: 2