Java:增加for循环中的变量

时间:2013-11-13 03:09:27

标签: java loops nested increment operator-keyword

我在初学者Java类中,对于一个项目,我需要计算一个条件在循环内部循环返回TRUE(correctGuess)或FALSE(incorrectGuess)的次数。我遇到的问题是,内循环中递增的变量在循环重复时不会保持其递增的值。因此,外部while循环的条件永远不会错误。我是编程新手,我无法找到解决方案。在这个愚蠢的问题上提前感谢你的时间,如果有任何问题,我会很高兴做一个更好的解释。代码如下所示:

    int incorrectGuess = 0;
    int correctGuess = 0;   

    while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {

        //Gets the users first guess
        System.out.print("Please guess a letter [A-Z]: ");
        letterGuessed = keyboard.nextLine();

        for (int i = 0; i < WORD_LENGTH; i++){
            char value = wordLetterArray[i];
            String letterArray_value = String.valueOf(value);

            if(letterGuessed.equals(letterArray_value)){
                ++correctGuess;
            }

            else
                System.out.println("Bad comparison!");  

            if(i == WORD_LENGTH)
                ++incorrectGuess;   

        }   
    }

1 个答案:

答案 0 :(得分:1)

看起来您可能需要重新设计整个算法,但我可以告诉您永远循环的主要问题是什么:

// Seems legit
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {

// Still seems legit
for (int i = 0; i < WORD_LENGTH; i++)

    // Well, there's a problem, i will never be equal to word length 
    //because a condition of the for loop is i < WORD_LENGTH
    if(i == WORD_LENGTH)
        ++incorrectGuess;   

同样,我觉得你需要重新设计你的整个算法,但是如果你想让它继续下去,只需从for循环中取出不正确的Guess增量线。这将为您提供预期的结果:

    for (int i = 0; i < WORD_LENGTH; i++){
      char value = wordLetterArray[i];
      String letterArray_value = String.valueOf(value);

      if(letterGuessed.equals(letterArray_value)){
            ++correctGuess;
      }
      else {
            System.out.println("Bad comparison!");  
      }
    }   

   incorrectGuess++;