简体   繁体   中英

Java: Incrementing a variable inside of a for loop

I am in a beginner Java class and for a project I need to count how many times a condition returns TRUE(correctGuess) or FALSE(incorrectGuess) with a loop inside of a loop. The problem that I'm having is that the variables being incremented within the inner loop do not hold their incremented value as the loop reiterates. Therefore, the outer while-loop's condition is never false. I'm really new to programming and I can't figure out the solution. Thank you in advance for your time with this silly question and if there are any questions I would be happy do a better explanation. The code looks like this:

    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;   

        }   
    }

Looks like you may need to redesign the whole algorithm, but I can tell you what your main issue is with this looping forever:

// 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;   

Again, I feel you need to redesign your whole algorithm, but if you want it to continue, just pull the incorrectGuess increment line out of the for loop. This will give you the intended result:

    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++;   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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