James N James N - 1 month ago 7
Java Question

exit program do-while loop in java

I am working on a java program. Right now everything is totally working, and all my functionality is there. However, the part I am stuck on is how to exit out of the program in a

do-while
loop. I must be getting the syntax wrong.

Basically, I set a switch
done
which reacts to a user's input. Right now, it's working and loops through the program, but it does not exit if I say "no" to continuing.

Here is the part of the code this is happening:

public void main() {
String userInput;
boolean done = true;
Scanner keyboard = new Scanner(System.in);
do {
System.out.println("Welcome to Hangman!");
System.out.println("Do you want to play?");
userInput = keyboard.next();
if (userInput.equals("Yes") || userInput.equals("yes") || userInput.equals("y") || userInput.equals("Y")) {
done = false;
} else if (userInput.equals("n") || userInput.equals("no") || userInput.equals("NO") || userInput.equals("No")) {
done = true;
}
while (!done) {
System.out.println(getDisguisedWord());
System.out.println("Guess a letter: ");
String guess = keyboard.next();
makeGuess(guess);
if (gameOver()) {
String ui;
System.out.println("Do you want to play again?");
ui = keyboard.next();
if (ui.equals("Yes") || ui.equals("yes") || ui.equals("y") || ui.equals("Y")) {
done = false;
} else {
done = true;
}
}
}
} while(done);
}


any tips on how I could handle this better?

Answer

Your problem isn't what you think it is. To compare Strings, you need to use their built-in equals() method: ui.equals("Y"). Using == to compare them will always return false. For more information, see How do I compare strings in Java?.

Also, you need to flip your done = true and done = false statements (if the user says yes to playing again, they aren't done yet).

Finally, I would recommend changing your keyboard.next() calls to keyboard.nextLine() calls, or else you may run into weird issues, especially if the user enters input that includes whitespace.

EDIT: I noticed some more issues. You're while loop should be while(!done) instead of while(done). Also, I would get rid of your do-while loop, because the while loop is already allowing the user to play as many times as they want, so it is unnecessary.

Comments