【问题标题】:finding index of highest value in array (Java)查找数组中最大值的索引(Java)
【发布时间】:2015-02-28 20:21:04
【问题描述】:

一段时间以来一直在处理 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 作为最高索引?如果我反转逻辑,该代码可以很好地检索最低索引,但我不确定我在这里做错了什么。感谢您的帮助。

【问题讨论】:

  • 这似乎主要是关于代码调试......它并没有试图提出一个简洁的问题。

标签: java arrays indexing


【解决方案1】:

因为你忘了更新最大值。

添加这一行:

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

【讨论】:

  • 嗯,好的。我现在明白了。正在检查我的参考资料,但没有看到更新声明。非常感谢。
  • @B__C 欢迎您,如果我的解决方案对您有帮助,您可以通过单击我的答案旁边的勾来接受我的解决方案。 (注意您只能接受一种解决方案)
  • 注意:for循环应该从1开始。因为你已经将highstValue分配给array[0]。
【解决方案2】:

您忘记更新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];
   }
}

【讨论】:

    【解决方案3】:

    您只关注从数组中获取索引,但是您忘记更新保持高值的最高值变量:

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

    【讨论】:

    • 虽然这个代码块可以回答这个问题,但如果你能提供一些解释为什么会这样,那将是一个更好的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多