如果语句忽略运算符?

时间:2014-08-13 02:47:04

标签: java loops if-statement for-loop

我正在尝试在for循环中运行if语句。然而,它似乎忽略了运营商......或其他什么。我试图让它给出包含最低总数的问题的数量和包含最高总数的数字。以下是方法:

这一个不断返回10:

public int topRatedQuestion(){

    int answerTotal = 0;
    int highScore = 0;
    int topQuestion = 0;

    for(int i = 0; i < 10; i++){

         for(int j = 0; j < 10; j++){

              answerTotal = answerTotal + answerArray[i][j];      
          } //close for (j)

          if (answerTotal >= highScore){

               highScore = answerTotal;
               topQuestion = i + 1;
          }

    }//close for (i)
    return topQuestion;   
}

每次都会返回1:

public int lowRatedQuestion(){

    int answerTotal = 0;
    int lowScore = 1000;
    int lowQuestion = 0;

    for(int i = 0; i < 10; i++){

        for(int j = 0; j < 10; j++){

            answerTotal = answerTotal + answerArray[i][j];        
        }//close for (j)

        if (answerTotal <= lowScore){

            lowScore = answerTotal;
            lowQuestion = (i + 1);                
        }

    }//close for (i)

    return lowQuestion;

}

1 个答案:

答案 0 :(得分:0)

由于您在外部for循环的下一次迭代期间没有刷新answertotal的值,因此发生错误。因此,这导致从2D阵列的前一行累积总量。     为了纠正代码,以这种方式初始化for循环之间的answertotal变量:

for(int i = 0; i < 10; i++){
            int answertotal=0;

     for(int j = 0; j < 10; j++){