0

I am currently making a Random Number Guessing Game. The game itself works fine, but I can't seem to get the Y/N (yes/no) loop working correctly. When I play the game, it doesn't even give me the option to input anything after I guess the correct number. I know it's probably a simple mistake, but I can't seem to figure it out. I even tried doing a "do-while" loop and that didn't seem to work.

    while (userWin == false) 
    {
        System.out.println ("Guess a number from 1 - 100: ");
        Scanner userInput = new Scanner (System.in);
        Random correctRandomNumber = new Random();
        int correctRandomNumberInt = correctRandomNumber.nextInt ((100) + 1);

        int guessCount = 0;
        int userGuessInt;


        while (userAnswer == 'Y')
        {

            userGuessInt = userInput.nextInt();
            guessCount = guessCount + 1;

            if (userGuessInt > correctRandomNumberInt)
            {
                System.out.println ("Too high! Guess again!");
            }
            else if (userGuessInt < correctRandomNumberInt)
            {
                System.out.println ("Too low! Guess again!");
            }
            else
            {
                userWin = true;
                System.out.println ("You win!");
                System.out.println ("Amount of guesses: " + guessCount + " to get the correct answer of " + correctRandomNumberInt + ".");

            }  
        }   
        System.out.println ("Wanna play again? Please answer with (Y/N): ");
        String userAnswerString = userInput.nextLine();
        if (userAnswerString.equals ("Y"))
        {
            userAnswer = 'Y';
        }
        else
        {
            userAnswer = 'N';
        } 
    }
}
JCD
  • 1
  • 1
    Don't create a new Scanner each time through the loop. Just create a single Scanner before the loop. Also, your inner loop never modifies userAnswer, so will never termionate. – FredK Feb 25 '20 at 23:31
  • What you've posted is not a [mre] but Fred's observation is correct; in addition to scanner problems, you have logic problems with your loop conditions. – khelwood Feb 25 '20 at 23:45
  • I just figured it out, thank you. I will make sure to shorten the code so it's more concise. – JCD Feb 26 '20 at 00:07

0 Answers0