0
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number");
int FirstNumber = scanner.nextInt();
System.out.println("Entered First Number is" + FirstNumber);
System.out.println("Enter Second Number");
int SecondNumber = scanner.nextInt();
System.out.println("Entered Second Number is" + SecondNumber);

There is no error in the mentioned code everything is perfect but I have a doubt about why we didn't write a scanner.next line() method to handle enter key being pressed after the first number is entered on the console.

2 Answers2

0

nextInt reads the next token in the scanner.

According to the documentation

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

And further down

The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace().

The documentation for Character.isWhitespace() says that it returns true if the given codepoint

[...] [...] is '\n', U+000A LINE FEED. [...]

Which means that \n is a separator, thus it's not part of any token, so you don't need to skip it with a dummy call to nextLine()

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
-1

Scanner.nextInt() does not read new lines, it only progresses in the current line. See: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

Alex_X1
  • 168
  • 10
  • That is not correct, it does progress to a next line (because scanner by default tokenizes on whitespace). However, say it is consuming `1\n2\n`, after two `nextInt()` calls the remaining buffer is `\n`. If you then ask for `nextLine()`, you get an empty line (and the remaining buffer is then empty). – Mark Rotteveel Dec 21 '22 at 16:34