Home > AI > Language > Java >

Scanner

Problem: nextLine() got skipped after nextInt().

Reason: it is because when using the nextInt(), you typed enter, nextInt() only consumes the int and the ‘\n’ is still in the buffer. So if you use nextLine() after the nextInt(), it will consumes the ‘\n’. You can attach nextLine() after each nextInt().

This would happen to other nextFoo() methods except nextLine.

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // consumes the '\n' in the buffer

System.out.print("Text1: ");
String text1 = input.nextLine();

System.out.print("Text2: ");
String text2 = input.nextLine();

Leave a Reply