User input to repeat program in Java

后端 未结 8 1284
遇见更好的自我
遇见更好的自我 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:28

    Here is the code:

    private Random num = new Random();
    
    private int answer = num.nextInt(10) +1;
    
    private int guess;
    
    private String playAgain;
    
    Scanner input = new Scanner(System.in);
    
    public void inputGuess(){
        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();
            }
    
            if(guess == answer) {
                System.out.println("Congratulations, You guessed the number!");
                System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
                playAgain = input.nextLine();
            }
    
        }while (!playAgain.equals("Y") && !playAgain.equals("y"));
    }
    

    You just need to introduce the winning/losing logic inside the while, and the condition will be the ending/continue flag.

    Another thing is always remember when comparing strings to use the equals method, since the == will compare the object reference and not the String value, in some cases == will return true for equal string since how JVM stores the Strings, but to be sure always use equals.

提交回复
热议问题