-1

I tried making a number guessing game from http://www.abgamerguys.com/tutorials/java-for-beginners-tutorial-day-3/ and I decided to add my own replay feature.

//Replay feature
boolean replay = true;
while (replay == true) {
    System.out.print("Do you want to play again? (y/n) : ");
    String askReplay = inputScanner.nextLine();

    if (askReplay.equalsIgnoreCase("y")) {
        playNumberGame = true;
        replay = false;
    } else if (askReplay.equalsIgnoreCase("n")) {
        playNumberGame = false;
        replay = false;
    } else {
        System.out.println("Unknown reply.");
    }
}

The problem is the final else statement runs before i give an input (y/n) and it loops again and then I am able to give an input and runs like it's supposed to.

This is the output I get:

Do you want to play again? (y/n) : Unknown reply.
Do you want to play again? (y/n) : 

Full code here.

Shantha Kumara
  • 2,679
  • 3
  • 32
  • 48
cyanoise
  • 1
  • 2
  • 6

3 Answers3

2

chances are, you read from the scanner before the while loop, and you didn't use nextLine, you used something like nextInt. This leaves characters remaining on that same line. YOu want to clear them out with a readLine() before the loop, so that when you ask in the loop, it will wait for you.

To be sure, however you should show what happens before the loop.

MeBigFatGuy
  • 27,244
  • 7
  • 57
  • 63
  • yep - looked at the whole code from the paste bin link. the previous scanner call is playerGuess = inputScanner.nextInt(); - there is a linefeed waiting in the buffer to be read. – slipperyseal Nov 26 '14 at 05:47
0

in your while loop use inputScanner.next(); and you will get the results youd like, like so

        boolean replay = true;
        while (replay == true) {
            System.out.print("Do you want to play again? (y/n) : ");
            String askReplay = inputScanner.next();

            if (askReplay.equalsIgnoreCase("y")) {
                playNumberGame = true;
                replay = false;
            } else if (askReplay.equalsIgnoreCase("n")) {
                playNumberGame = false;
                replay = false;
            } else {
                System.out.println("Unknown reply.");
            }

        }
JRowan
  • 6,520
  • 6
  • 34
  • 57
0

I just tested it, and it's a simple fix.

Change:

String askReplay = inputScanner.nextLine();

to

String askReplay = inputScanner.next();

next() will wait regardless of the state of the line already called in due to whitespace or a return character.

James Taylor
  • 5,468
  • 6
  • 42
  • 62