【问题标题】:For loop containing if statements does not loop again包含 if 语句的 for 循环不再循环
【发布时间】:2015-03-29 07:50:45
【问题描述】:

下面是一个方法,它接受studentarray 和topStudentIndex 的值,该值是由之前的另一种方法计算得出的。

我的数组中有多个对象。但是for循环只循环了一次,直接返回了第一个值。

我不知道为什么 for 循环停止了,即使我的 st.length 超过了

public static int computeNextHighestOverallStudentIndex(Student[] st, int topStudentIndex) {

    double nextHighestOverall= 0;
    int nextHighestStudentIndex = 0;
    for (int i = 0; i < st.length; i++) {
            if ((st[i] != null) && (!(i == topStudentIndex))){
                double studentOverall = st[nextHighestStudentIndex ].getOverall();
                if (studentOverall > nextHighestOverall) {
                    nextHighestOverall= studentOverall;
                    nextHighestStudentIndex = i;
                }
            }
        }
    return nextHighestStudentIndex ;
}

【问题讨论】:

    标签: java arrays for-loop netbeans


    【解决方案1】:

    看起来像

    double studentOverall = st[nextHighestStudentIndex ].getOverall();
    

    应该是

    double studentOverall = st[i].getOverall();
    

    因为您要检查数组中的所有学生,而不仅仅是第一个(st[nextHighestStudentIndex ] 将始终返回第一个学生,因为您将 nextHighestStudentIndex 初始化为 0)。

    【讨论】:

    • 谢谢@Eran,更改后它起作用了。我会马上接受你的回答,让计时器到期
    【解决方案2】:

    您想使用 st[i](而不是 st[nextHighestStudentIndex])遍历整个数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多