Guess a number program with Java

前端 未结 6 1744
情话喂你
情话喂你 2021-01-28 12:06

I am trying to create a program in Java in which the computer randomly guesses a number between 1-100 and allows the user to guess to the number.

If the number is lower

6条回答
  •  我在风中等你
    2021-01-28 12:40

    You weren't getting another input, or keeping count. Try this

    public static void main(String args[]) {
        Scanner keyboard = new Scanner(System.in);
        int count = 0;
        int a = 1 + (int) (Math.random() * 99);
        int guess = 0;
    
        System.out.println("I am thinking of a number from 1 to 100"
            + " ... guess what it is ?");
    
        while (guess != a) {
            guess = keyboard.nextInt();
            count++;
            if (guess > a) {
                System.out.println("lower!");
            } else if (guess < a) {
                System.out.println("higher!");
            }
        }
        System.out.println("Congratulations. You guessed the number with "
            + count + " tries!");
    }
    

    Output

    I am thinking of a number from 1 to 100 ... guess what it is ? 
    50
    higher!
    75
    lower!
    62
    Congratulations.   You guessed the number with 3 tries!
    

提交回复
热议问题