Java 5 introduced Scanner class which has a functionality similar to the Reader in addition to the StringTokenizer class. Scanner can read input from a File, InputStream and ReadableByteChannel and can tokenize this data. It is more powerful than StringTokenizer, because it can parse primitives directly instead of taking them as String and parsing them to the corresponding primitive type.
Assume that we want to take the user input which consists of two Strings (e.g. name and last name) and an integer (e.g. student number).
Let's see how Scanner class works:
First we will link scanner to some input source.
2 | Scanner scanner = new Scanner(System.in); |
Then Scanner will take the input from user and parse the input values to desired variables.
1 | String name = scanner.next(); |
2 | String lastName = scanner.next(); |
3 | int studentNumber = scanner.nextInt(); |
It is also possible to parse numbers with base other than decimal.
2 | int number = scanner.nextInt(); |