ports
ports

Reputation: 17

Java unending while loop

Okay so I am a total noob when it comes to Java so apologies if this is a stupid question. I have a while loop set up like so:

do {
  //quiz questions, lose a life when you get one wrong
} while (livesRemain > 0) 

However, when you lose all of your lives the loop does not end and continues through the loop even when all lives are lost. Would I use something else other than while or do while that will end when a certain condition is reached?

The questions are like this:

 System.out.print(question1) 
    if (guess == 1) {
    System.out.print("Correct")
    score++;
    } else {
    livesRemain--;
}

When you reach the end of the quiz, it prints your score which ends up going into the negatives if you go below 0.

Upvotes: 0

Views: 306

Answers (2)

user3437460
user3437460

Reputation: 17474

The reason why the loop is not ending:

enter image description here

  • When you are inside the do-while loop, it will remain in the loop as long as the condition meets (i.e. liveRemaining > 0)
  • The variable livesRemaining is decremented outside the loop.
  • Hence, livesRemaining is always > 0 since you are not updating it anywhere in the loop.
  • Resulting loop not to end.

Would I use something else other than while or do while that will end when a certain condition is reached?

The issue is not with choosing a suitable loop. The problem is caused by terminating condition not updated. To solve this problem, bring your codes into the loop so that the terminating condition can be met.

do{
    //Ask question..
    if(guess == 1)
        System.out.println("Correct");
    else
        livesRemain--;     //Update livesRemain
}while(livesRemain > 0);   //Keeping asking questions till lives == 0   

Upvotes: 1

thegauravmahawar
thegauravmahawar

Reputation: 2823

You should try something like:

do {
      if(wrong) 
        livesRemain--;
} while (livesRemain > 0) 

Upvotes: 5

Related Questions