We now arrive at the core concept of how the Scanner works.
In this topic, we’ll explore how the next() method works, which serves as the basis for how other subtypes of next() also work.
User Input
Consider the code below:
public class Main {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.next();
System.out.println("You entered: " + str);
}
}One first step in learning how it works is that if there are no input tokens to scan (which usually occurs at the beginning of the code execution), it first awaits for a user input.
This user input will then be divided into input tokens based on how we discussed them in Basic Terminology.
For example, if our input is
abcdef1234;@ zyxwvu0987}!
It will be divided as:
Once the input string has been divided into tokens, the program will now begin scanning for tokens.
Scanning the Input Stream
Once there are tokens to scan, the Scanner retrieves the first token in the input stream, which in this case is abcdef1234;@.
Then, it removes that token from the stream and returns that value.
Therefore, using our code from above as an example, we can say that if the input is:
abcdef1234;@ zyxwvu0987}!
Then it will output:
You entered: abcdef1234;@
However, once there are still remaining tokens in the input stream, it would not await for input and will scan the next token in the input stream instead.
Therefore, if we modify our setup, like this:
public class Main {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = scan.next();
System.out.println("You entered: " + str1);
String str2 = scan.next();
System.out.println("You entered: " + str2);
}
}And then we placed our input:
abcdef1234;@ zyxwvu0987}!
It would then output:
You entered: abcdef1234;@
You entered: zyxwvu0987}!
without having to do any user inputs in the second instance of next().
The Process
To summarize how the Scanner scans up inputs and outputs with next():
- If there are no tokens in the input stream, the program awaits for user input.
- The user input is parsed as a single input string.
- The original input string (separated by delimiters) now becomes split into tokens, which forms the input stream.
- If there are tokens in the input stream,
Scannerremoves them from the stream, and becomes the return value for that function
Therefore, there can be cases where a call for next() will simply not await for a user input and simply process the next token.