Home > Back-end >  Why there is no scanner.nextline() method between two nextInt() methods
Why there is no scanner.nextline() method between two nextInt() methods

Time:12-21

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.

CodePudding user response:

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()

CodePudding user response:

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()

  • Related