2
votes

I need to create a simple game where a random number is created, and the user has to guess the number by inputting numbers into a scanner. If their guess is too high, the system tells them to guess lower, and the same if it is too low.

I'm using a while loop, but I don't know how to continuously call the scanner so that the user can keep guessing. Here is my code so far:

public static void highLow()
{
  Random randomGenerator = new Random();
  int num = randomGenerator.nextInt(100);
  boolean loop = true;

  while(loop)
  {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter a number: ");
    int numGuess  = scanner.nextInt();
        if (numGuess > num)
          System.out.println("Guess lower!");
          scanner.nextInt();

        if (numGuess < num)
          System.out.println("Guess higher!");
          scanner.nextInt();

        if (numGuess == num)
          System.out.println("Correct! You win!!!");
          loop = false;
  }
}
1
Welcome to Stack Overflow! FYI, if you're learning Java, you might want to check out Code Review where you can get lots of tips for improvement. - Nate Barbettini

1 Answers

1
votes

You're almost there. Here are some suggestions:

  1. Assign the input of the Scanner back into numGuess in order to have the value "ready" for the next loop iteration.
  2. Use braces after your if conditions.
  3. You don't have to redeclare the Scanner object each time. Do it once, before the loop.

It was a combination of #1 and #2 that was causing your code to fail before. Look closely at your if blocks. If you leave off the braces, only the first line following is part of the if. (see Is it ok if I omit curly braces in Java?)

So, you meant this:

if (numGuess == num)
    System.out.println("Correct! You win!!!");
    loop = false;

But what the compiler "saw" was really this:

if (numGuess == num)
    System.out.println("Correct! You win!!!");
loop = false;

The misplaced loop = false will ensure that your loop only ever runs once, no matter what the user entered. Explicitly including braces keeps it unambiguous!

Here's what your code looks like after making the above changes:

public static void highLow()
{
    Random randomGenerator = new Random();
    int num = randomGenerator.nextInt(100);
    boolean loop = true;
    Scanner scanner = new Scanner(System.in);
    int numGuess = 0;

    while(loop)
    {
        System.out.print("Please enter a number: ");
        numGuess  = scanner.nextInt();
        if (numGuess > num) {
            System.out.println("Guess lower!");
            numGuess  = scanner.nextInt();
        } else if (numGuess < num) {
            System.out.println("Guess higher!");
            numGuess  = scanner.nextInt();
        } else if (numGuess == num) {
            System.out.println("Correct! You win!!!");
            loop = false;
        }
    }
}