Issue I have is with yes/no statement, if I enter "no" it will continue instead to exit the program. Please if someone can give me tip where issue is?
import java.util.Random; import java.util.Scanner;
public class NumberGame { private static final int DO_NOT_PLAY_AGAIN = 0;
private final Scanner mScanner;
private final Random mRandom;
private String mUserName;
private int mCorrectAnswer;
private int mPlayAgainInput;
private String mAnswer;
public NumberGame() {
mScanner = new Scanner(System.in);
mRandom = new Random();
}
public void run() {
displayWelcomeMessage();
getUserName();
greetUser();
getAnswer();
do {
intNumberGuessGame();
} while (mPlayAgainInput != DO_NOT_PLAY_AGAIN);
sayGoodbye();
}
private void getAnswer(){
System.out.println("Would you lioke to play a game enter yes to play or no to exit a game");
mAnswer = mScanner.nextLine();
if (mAnswer.equals("no"))
System.out.println("Maybe next time");
sayGoodbye();
}
private void displayWelcomeMessage() {
System.out.println("Welcome to the game!");
System.out.println("To play this game you have to"
+ " guess a number and enter upon prompt or you can"
+ " enter 0 to quit the game.");
}
private void getUserName() {
System.out.println("Enter your user name: ");
mUserName = mScanner.nextLine();
}
private void greetUser() {
System.out.println("Let's play a game, " + mUserName + ".");
}
private void sayGoodbye() {
System.out.println("Thanks for playing, " + mUserName + "!");
}
private void intNumberGuessGame() {
// Get a random number between 1 - 100
Random generator = new Random();
mCorrectAnswer = mRandom.nextInt(100) + 1;
int theirGuess = 0;
int howManyTries = 0;
while (theirGuess != mCorrectAnswer) {
System.out.println("Guess my number: ");
theirGuess = mScanner.nextInt();
mCorrectAnswer = mRandom.nextInt(101) + 1;
howManyTries++;
System.out.println("Correct answer = " + mCorrectAnswer);
if (theirGuess == mCorrectAnswer) {
System.out.println("You guessed it! It only took you "
+ howManyTries + " tries to get it right!");
promptToPlayAgain();
// They won the game, exit current loop
break;
} else if (theirGuess > mCorrectAnswer) {
System.out.println("Your answer is too high.");
} else if (theirGuess < mCorrectAnswer) {
System.out.println("Your answer is too low.");
}
}
}
private void promptToPlayAgain() {
System.out.println("Do you want to play again? (0 to quit): ");
mPlayAgainInput = mScanner.nextInt();
}
}
public class MainApp {
public static void main(String[] args) {
new NumberGame().run();
}
}
mPlayAgainInput = mScanner.nextInt();. Why are you assuming if it scans in "no" that it will exit the game? - BLaZuRE