Reputation: 17
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
Reputation: 17474
The reason why the loop is not ending:
liveRemaining > 0
)livesRemaining
is decremented outside the loop.livesRemaining
is always > 0 since you are not updating it anywhere in the loop.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
Reputation: 2823
You should try something like:
do {
if(wrong)
livesRemain--;
} while (livesRemain > 0)
Upvotes: 5