简体   繁体   中英

While loop in a number guessing game

I need to write code that asks you to guess a number between 1 and 10 and uses a loop. It has to use the System.in.read() method to take user input. The correct number is 7, and when you guess that it ends. If you guess wrong it tells you to try again. I don't know why my code isn't working right, so I could use some help. The output I get is weird, no matter what number I enter it just says:

  • Hello! Enter a number between 1 and 10:
  • (entered number ex. 4)
  • Your guess is too high
  • Hello! Enter a number between 1 and 10:
  • Your guess is too high
  • Hello! Enter a number between 1 and 10:

I am new to programming so sorry if it isn't indented right or the solution is obvious.

public static void main(String[] args) throws java.io.IOException {
    int input;
    boolean play = true;
    while (play == true) {
        System.out.println("Hello! Enter a number between 1 and 10: ");
        input = System.in.read();
        if (input > 7) {
            System.out.println("Your guess is too high");
        } else if (input < 7) {
            System.out.println("Your guess is too low");
        } else if (input == 7) {
            System.out.println("Correct! the correct number was: 7"); 
        }
    }
}

It should give you a specific result depending on the number, like if it is too high or low, then you can try again and enter a new number until you get the correct answer of 7. If the number isn't 1-10 you should get an error message. Thanks.

You're not changing the play variable, so there is no goin out of the while loop. You would have to change it like this:

else if (input == 7) {
    System.out.println("Correct! the correct number was: 7"); 
    play = false;
}

Also you might want to move this line: System.out.println("Hello! Enter a number between 1 and 10: "); before while loop.

This might solve your problem.

public static void main(String[] args) {

    int input;
    boolean play = true;
    Scanner inputNumber = new Scanner(System.in);
    while (play) {
        System.out.println("Hello! Enter a number between 1 and 10: ");
        input = inputNumber.nextInt();
        if (input > 7) {
            System.out.println("Your guess is too high");
        } else if (input < 7) {
            System.out.println("Your guess is too low");
        } else if (input == 7) {
            System.out.println("Correct! the correct number was: 7");
            play = false;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM