简体   繁体   English

如果语句忽略运算符?

[英]If statement ignoring operator?

I'm trying to run an if statement inside of my for loop. 我试图在我的for循环中运行if语句。 However, it seems to be ignoring the operators...or something. 但是,它似乎在忽略操作员……等。 I'm trying to get it to give the number of the question that contains the lowest total and the number that contains the highest total. 我试图让它给出包含最低总数的问题的数量和包含最高总数的问题的数量。 Here are the methods: 方法如下:

This one keeps returning 10: 这个不断返回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;   
}

This one returns 1 everytime: . 每次返回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;

}

The error is occurring due to the fact that you are not refreshing the value of answertotal during the next iteration of the outer for loop. 发生错误是由于您在外部for循环的下一次迭代期间未刷新answertotal的值。 This is thus leading to the accumulation of the total from the previous row of the 2D-array. 因此,这导致2D数组前一行的总数累积。 In order to correct the code initialize the answertotal variable between the for loops in this way: 为了更正代码,可以使用以下方式在for循环之间初始化answertotal变量:

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

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

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

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