The Scanner class also helps when you want the user to be able to type more than one value on a line. Suppose we want to read in an age, a height and the number of children. So the data might be something like:
42 1.85 2Before Java 5, you would need to use something like StringTokenizer to break apart a line into separate items (often called tokens):
0100: String tLine = tKeyboard.readLine(); 0101: StringTokenizer tTokens = new StringTokenizer(tLine); 0102: String tAgeString = tTokens.nextToken(); 0103: int tAge = Integer.parseInt(tAgeString); 0104: String tHeightString = tTokens.nextToken(); 0105: double tHeight = Double.parseDouble(tHeightString); 0106: String tNumberOfChildrenString = tTokens.nextToken(); 0107: int tNumberOfChildren = Integer.parseInt(tNumberOfChildrenString);
However, the nextXXX methods of the Scanner class can cope with several items being on the same line. So the data:
42 1.85 2can be read by the following code:
0120: int tAge = tScanner.nextInt(); 0121: double tHeight = tScanner.nextDouble(); 0122: int tNumberOfChildren = tScanner.nextInt();
By default, tokens are assumed to be separated by whitespace. However, you can easily arrange for the scanner to use delimiters other than whitespace.