User input to repeat program in Java

后端 未结 8 1302
遇见更好的自我
遇见更好的自我 2020-12-11 11:41

I am writing a simple guessing game program where the user will input a number to try and guess a randomly generated number.

If they get the number right I want to

8条回答
  •  余生分开走
    2020-12-11 12:20

    Here is the completed code, fully working and tested... without using recursion.. and everything fixed.

        public static void main(String[] args)
        {
        String playAgain = "";
        Scanner scan = new Scanner(System.in);
    
        do
        {
            ClassName.inputGuess();
            System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
            playAgain = scan.nextLine();
        }
        while(playAgain.equalsIgnoreCase("Y"));
        System.out.println("Thanks for playing!");
    }
    
    public void inputGuess()
    {
        Random num = new Random();
        int answer = num.nextInt(10)+1;
        Scanner input = new Scanner(System.in);
        int guess;
    
        System.out.println("Enter a number between 1 and 10 as your first guess: ");
        guess = input.nextInt(); 
    
        do
        {
            if (guess < 1 || guess > 10)
            {
                System.out.println("That is not a valid entry. Please try again: ");
                guess = input.nextInt();
            }
            else 
                if (guess > answer)
                {
                    System.out.println("Too high, Try Again: ");
                    guess = input.nextInt();
                }
                else 
                    if (guess < answer)
                    {
                        System.out.println("Too low, Try Again: ");
                        guess = input.nextInt();
                    }
            input.nextLine();
    
        }
        while (guess != answer);
    
        System.out.println("Congratulations, You guessed the number!");
    }
    

提交回复
热议问题