Categories
io java java.util.scanner

Scanner is skipping nextLine() after using next() or nextFoo()?

895

I am using the Scanner methods nextInt() and nextLine() for reading input.

It looks like this:

System.out.println("Enter numerical value");    
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string"); 
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)

The problem is that after entering the numerical value, the first input.nextLine() is skipped and the second input.nextLine() is executed, so that my output looks like this:

Enter numerical value
3   // This is my input
Enter 1st string    // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string    // ...and this line is executed and waits for my input

I tested my application and it looks like the problem lies in using input.nextInt(). If I delete it, then both string1 = input.nextLine() and string2 = input.nextLine() are executed as I want them to be.

1

  • 10

    Or you could be like me and use BufferedReader 🙂 I don’t care if it’s old school, it has always worked and always will work for me. Also, knowledge of BufferedReader has application elsewhere. I simply don’t like Scanner.

    – Cruncher

    Aug 27, 2013 at 19:36

1092

That’s because the Scanner.nextInt method does not read the newline character in your input created by hitting “Enter,” and so the call to Scanner.nextLine returns after reading that newline.

You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

Workaround:

  • Either put a Scanner.nextLine call after each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline

    int option = input.nextInt();
    input.nextLine();  // Consume newline left-over
    String str1 = input.nextLine();
    
  • Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method.

    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    String str1 = input.nextLine();
    

12

  • 9

    @blekione. You have to use try-catch, because Integer.parseInt throws NumberFormatException when an invalid argument is passed to it. You will learn about exception later on. For E.G: – Integer.parseInt("abc"). You don’t want “abc” to get converted to int right?

    Oct 27, 2012 at 18:02

  • 3

    @blekione. So, in the above case, your code will halt at that point, and you won’t be able to continue the execution. With Exception Handling, you can handle such kind of conditions.

    Oct 27, 2012 at 18:02

  • 4

    To which extent is the latter better? AFAIK Scanner#nextInt() is way more lenient in finding correct ints, by allowing group commas and locale prefixes and suffixes. Integer#parseInt() allows digits and decimal point only plus an optional sign.

    – Mordechai

    Jan 11, 2017 at 3:00


  • 6

    I personally prefer a Scanner#hasNextFoo check beforehand instead of a try-catch, but that works too.

    Jan 22, 2017 at 1:13

  • 1

    Use ParseDouble has a new problem, that nextDouble use the regional configuration of decimal (. or ,) but Parsedouble always receive US decimal ( . ).

    – olmerg

    Oct 24, 2017 at 21:58

262

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. So to skip this you have to add the input.nextLine(). Hope this should be clear now.

Try it like that:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

3

  • umm seems a solution, making the skipped line non-used nextLine, but I still need an explanation of this behaviour

    – Eng.Fouad

    Aug 14, 2011 at 12:25


  • 2

    FYI: merged from stackoverflow.com/questions/7056749/…

    – Shog9

    Nov 13, 2014 at 19:11

  • If that is the case, Why don’t we encounter the same problem if we use Scanner.next() call after Scanner.nextInt(). Why don’t I get a blank string in Scanner.next() ?

    – Tushar

    Apr 15, 2021 at 10:02

92

It’s because when you enter a number then press Enter, input.nextInt() consumes only the number, not the “end of line”. When input.nextLine() executes, it consumes the “end of line” still in the buffer from the first input.

Instead, use input.nextLine() immediately after input.nextInt()

5

  • 8

    @Victor it’s not bug. it’s working as specified. you could argue though that there should be an easy way to tell the api to also consume any whitespace following the target input.

    – Bohemian

    May 29, 2014 at 13:38

  • 1

    I see. thanks @Bohemian, that exactly what i am arguing. I think that this should be changed, perhaps you can point me where to suggest this “issue” in the next JCP.

    – Victor

    May 29, 2014 at 14:55

  • @victor You can request (and find out how to contribute code to) a feature via the Report a Bug or Request a Feature page.

    – Bohemian

    May 29, 2014 at 15:18

  • FYI: merged from stackoverflow.com/questions/7056749/…

    – Shog9

    Nov 13, 2014 at 19:12

  • If that is the case, Why don’t we encounter the same problem if we use Scanner.next() call after Scanner.nextInt(). Why don’t I get a blank string in Scanner.next() ?

    – Tushar

    Apr 15, 2021 at 10:02