Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java .nextLine() repeats line

Tags:

java

Everything of my guessing game is alright, but when it gets to the part of asking the user if he/she wants to play again, it repeats the question twice. However I found out that if I change the input method from nextLine() to next(), it doesn't repeat the question. Why is that?

Here is the input and output:

I'm guessing a number between 1-10
What is your guess? 5
You were wrong. It was 3
Do you want to play again? (Y/N) Do you want to play again? (Y/N) n

Here is the code:(It is in Java) The last do while loop block is the part where it asks the user if he/she wants to play again.

import java.util.Scanner;

public class GuessingGame 
{   
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        boolean keepPlaying = true;

        System.out.println("Welcome to the Guessing Game!");

        while (keepPlaying) {
            boolean validInput = true;
            int guess, number;
            String answer;

            number = (int) (Math.random() * 10) + 1;
            System.out.println("I'm guessing a number between 1-10");
            System.out.print("What is your guess? ");
            do {
                validInput = true;
                guess = input.nextInt();
                if (guess < 1 || guess > 10) {
                    validInput = false;
                    System.out.print("That is not a valid input, " +
                            "guess again: ");
                }
            } while(!validInput);
            if (guess == number)
                System.out.println("You guessed correct!");
            if (guess != number)
                System.out.println("You were wrong. It was " + number);
            do {
                validInput = true;
                System.out.print("Do you want to play again? (Y/N) ");
                answer = input.nextLine();
                if (answer.equalsIgnoreCase("y"))
                    keepPlaying = true;
                else if (answer.equalsIgnoreCase("n"))
                    keepPlaying = false;
                else
                    validInput = false;
            } while (!validInput);
        }
    }
}
like image 777
Chris L. Avatar asked Aug 19 '13 18:08

Chris L.


People also ask

Why do I have to use nextLine twice?

I suspect you are reading something (such as an integer) elsewhere which leaves a newline in the input. So the when you call this method, that newline is consumed by the first nextLine() call. Hence, it appears to skip one input (or requiring you to have two nextLine() calls).

What is the problem with nextLine in Java?

The problem is with the input. nextInt() method - it only reads the int value. So when you continue reading with input. nextLine() you receive the "\n" Enter key.

Why does nextLine skip a line?

This is happening because of the Scanner. nextInt method does not read the newline character in the input generated by hitting "Enter," and so the call to Scanner. nextLine retorts after reading that newline.

Does nextLine read in the new line?

nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end.


1 Answers

In your do while loop, you don't want the nextLine(), you just want next().

So change this:

answer = input.nextLine();

to this:

answer = input.next();

Note, as others have suggested, you could convert this to a while loop. The reason for this is that do while loops are used when you need to execute a loop at least once, but you don't know how often you need to execute it. Whilst it's certainly doable in this case, something like this would suffice:

System.out.println("Do you want to play again? (Y/N) ");
answer = input.next();
while (!answer.equalsIgnoreCase("y") && !answer.equalsIgnoreCase("n")) {
    System.out.println("That is not valid input. Please enter again");
    answer = input.next();
}

if (answer.equalsIgnoreCase("n"))
    keepPlaying = false;

The while loop keeps looping as long as "y" or "n" (ignoring case) isn't entered. As soon as it is, the loop ends. The if conditional changes the keepPlaying value if necessary, otherwise nothing happens and your outer while loop executes again (thus restarting the program).

Edit: This explains WHY your original code didn't work

I should add, the reason your original statement didn't work was because of your first do while loop. In it, you use:

guess = input.nextInt();

This reads the number off the line, but not the return of the line, meaning when you use:

answer = input.nextLine();

It immediately detects the leftover carriage from the nextInt() statement. If you don't want to use my solution of reading just next() you could swallow that leftover by doing this:

guess = input.nextInt();
input.nextLine();
rest of code as normal...
like image 130
Andrew Martin Avatar answered Sep 29 '22 09:09

Andrew Martin