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.
-
1This seems to be mostly about code debugging...it doesn't attempt to ask a succinct question.Maarten Bodewes– Maarten Bodewes2015年02月28日 20:29:29 +00:00Commented Feb 28, 2015 at 20:29
2 Answers 2
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
How to find your mistake:
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.");
}
}
-
Ahh ok. I see now. Was checking my references and did not see an update statement. Thank you very much.B__C– B__C2015年02月28日 20:43:21 +00:00Commented Feb 28, 2015 at 20:43
-
Note: For loop should start with 1. Because you has already assigned highstValue to array[0].Sedat Polat– Sedat Polat2015年03月07日 22:12:47 +00:00Commented Mar 7, 2015 at 22:12
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];
}
}