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

It is common for the Scanner class's next() and nextFoo() methods (where Foo is any primitive type such as Int, Double, etc.) to skip over newline characters in the input. This is because these methods are designed to read only the next token in the input, and a token is defined as a sequence of characters that does not include any white space characters.

Newline characters, like all white space characters, serve to separate tokens in the input. When the Scanner reads a token using one of the next() or nextFoo() methods, it consumes all the characters in the token, including any white space characters that come after the token, but not including any white space characters that come before the token.

If you want to read the entire line of input, including any white space characters, you can use the Scanner class's nextLine() method. This method reads the rest of the current line, up to and including the newline character that terminates the line.

If you have already used a next() or nextFoo() method to read a token from the input and you want to read the rest of the line, you can call the nextLine() method immediately after the next() or nextFoo() method. This will consume the rest of the current line, including any white space characters and the newline character.

For example:

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();  // reads an integer from the input
scanner.nextLine();  // consumes the rest of the line, including the newline character

String line = scanner.nextLine();  // reads the next line of input

In this example, the call to nextInt() reads an integer from the input and consumes the rest of the token, including any white space characters that come after the integer. The call to nextLine() then consumes the newline character that follows the integer and any other white space characters on the same line. The next call to nextLine() then reads the next line of input.