Can anyone tell me, when I'm hitting y/n - why does my game not stop, it only starts again. I'm calling my isDone() method before the run, but it just runs over and over again and again.
public class Model {
int numberToGuess = 29;
int counter;
boolean isDone;
Scanner sc = new Scanner(System.in);
public Model() {
isDone = false;
run();
}
public void run() {
welcomeMessage();
while (true) {
guessNumber();
}
}
public void welcomeMessage() {
System.out.println("Welcome to " + '\n' + "***** GUESS THE NUMBER *****");
}
public void guessNumber() {
System.out.println("Please enter number and hit 'Enter'" + '\n');
if (sc.hasNextInt()) {
int input = sc.nextInt();
counter++;
if (input < numberToGuess) {
System.out.println('\n' + "Your guess is too low!" + '\n');
} else if (input > numberToGuess) {
System.out.println('\n' + "Your guess is too high!" + '\n');
} else {
System.out.println("Congratulations, you guessed the number!" + '\n' + "You guessed the number in " + counter + " guess." + '\n');
isDone();
}
} else {
System.out.println("Invalid input, please enter a number!" + '\n');
sc.next();
}
}
public void isDone() {
System.out.println("Do you wanna play again? Enter y/n");
if (sc.hasNext()) {
String input = sc.next();
if ("y".equals(sc))
if (input.equals("y")) {
isDone = false;
guessNumber();
} else if (input.equals("n")) {
isDone = true;
}
}
System.out.println("Invalid input, please enter y/n to continue");
sc.next();
}
}
You have an infinite loop:
while (true)
Theres no condition to terminate the program.
You could use your global isDone variable and replace the true with:
while (!isDone)
{
guessNumber();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With