0

I'm trying to make a program that takes input of a minimum and a maximum number and then generates a random number in that range. Then the user guesses a number and if it's too high, it outputs a messege.. If it's too low, it outputs a message. The part that i'm stuck at is when you guess the number correctly, the user inputs "Y" or "N" to run the program again.

My code is as follows:

import java.util.Scanner;
import java.util.Random;
public class GuessingGame_V2
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.print('\u000C');
        int min;
        int max;
        int userGuess;
        int numberGuesses = 1;   
        System.out.println("Enter the minimum number: ");
        min = in.nextInt();
        System.out.println("Enter the maximum number: ");
        max = in.nextInt();
        Random r = new Random();
        int randomNumber = r.nextInt(max - min + 1) + min;
        System.out.println("Enter your guess: ");
        userGuess = in.nextInt();
    String guessAgain = ("Y");
while(!guessAgain.equalsIgnoreCase("N"))
{         
    if( userGuess > randomNumber ){
        System.out.println("Your guess was to high! Guess again!");
        System.out.println("Input your new guess: ");
        userGuess = in.nextInt();
        numberGuesses++;
       }
    else if (userGuess < randomNumber ){
        System.out.println("Your guess was to low! Guess again!");
        System.out.println("Input your new guess: ");
        userGuess = in.nextInt();
        numberGuesses++;
       }
    else 
       {  
        System.out.println("Congratulations, you guessed the number!");
        System.out.println("It took " + numberGuesses + " tries");
        System.out.println("Guess another number? (Y/N)");
        guessAgain = in.next();
       }
    }
   System.out.println("Thank's for playing!");
   }
}

The problem comes when the user hits "Y" to restart the program. It doesn't restart and just displays the final message again. (print statement, number of guesses, and Y/N). I need the program to restart when the user types "Y"

I'm new to posting on the site.. so forgive me if I messed up putting in the code - Thanks in advance for the help -

*Changes - 11/13/13 10:58 Changed the code to take more than one input and to keep taking input until the user gets it right.

4

1 に答える 1