next()
and nextLine()
have very different behaviors so you cannot just change them out arbitrarily. In particular, the nextLine
behavior is very nuanced. Here is the Javadoc describing it:
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
NOTE: By “current line” it means “wherever the current pointer happens to be” which may include some already buffered content.
The next()
method will return the next “token” which by default breaks on any whitespace, so you could not enter a full name with a space using the next
method. Here is its Javadoc:
Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of
hasNext(Pattern)
returnedtrue
. If the match is successful, the scanner advances past the input that matched the pattern.
So when the next()
method is called, it also has to read the whole line up to the next newline so something like “praveen\n” is put into the buffer (where “\n” is the newline). It uses the newline as a delimiter for the token that it returns so it returns “praveen” leaving the newline in the buffer “\n”. Then when nextLine()
is called, the already buffered content already contains a new line so it just returns everything preceeding that newline (which is nothing) without grabbing anything else from System.in
(emptying the buffer).
It is easier to see if you wrapped the “role” printed out with single quotes:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
Byte age = scanner.nextByte();
System.out.println("Age is: " + age);
System.out.print("Enter name: ");
String name = scanner.next();
System.out.printf("You are: '%s'%n", name);
System.out.print("Enter role: ");
String role= scanner.nextLine();
System.out.printf("Role is: '%s'%n", role);
If you want to clear out that buffer, you need to call readLine()
a second time so that we get past the buffered newline and then it will block until you get new input through System.in
. To keep it clear what we are doing, we can clear the buffer directly after we get the name:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
Byte age = scanner.nextByte();
System.out.println("Age is: " + age);
System.out.print("Enter name: ");
String name = scanner.next();
scanner.nextLine();
System.out.printf("You are: '%s'%n", name);
System.out.print("Enter role: ");
String role= scanner.nextLine();
System.out.printf("Role is: '%s'%n", role);
This prints out the expected results.