繁体   English   中英

查找数组中最高价值的索引(Java)

[英]finding index of highest value in array (Java)

一段时间以来一直在解决Java问题。 获取与最大值对应的数组索引时遇到问题。 我很确定我了解这样做的逻辑,因为我成功检索了包含最低值的索引。 这就是我所拥有的:

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);

}

但是,对于此数组,我的代码返回的索引为10,对应于6.6。 但是数组中的最高值是索引6处的12.12。为什么我总是将10作为最高索引? 如果我颠倒逻辑,该代码可以很好地检索最低索引,但是我不确定自己在做什么错。 谢谢你的帮助。

因为您忘记更新最高值。

添加此行:

highestValue = array[i];

将您的代码更改为:

   if (array[i] > highestValue) {
        highIndex = i;
        highestValue = array[i];   //Add this line
   }

如果不更新最大值,则始终与数组中的第一个元素进行比较。

证明:

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

如何发现错误:

您可以通过在代码中添加几行println语句来进行自己的测试,如下所示。 (使用调试器的替代方法)

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.");
   }           
}

您忘了更新highestValue 因此, array[i]高于array[0]每个i都会导致highIndex被更新。 10是最后一个这样的索引。

您的代码应如下所示:

for (int i = 0; i < array.length; i++) {
   if (array[i] > highestValue) {
       highIndex = i;
       highestValue = array[i];
   }
}

您只关注从数组中获取索引,但是却忘记了更新其中保留了高值的highestValue变量:

for (int i = 0; i < array.length; i++) {
   if (array[i] > highestValue ){            
       highIndex = i;
       highestValue=array[i];
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM