Keyboard Input with the Scanner Class

Java programmers no longer need to wade through a design pattern or use a third-party toolkit for keyboard input. The Scanner class of Java 5.0 supports easy keyboard input of all primitive data types as well as lines of text. The next code segment shows how to set up a scanner and input data of various types:

 

import java.util.Scanner;

 

Scanner reader = new Scanner(System.in);

System.out.print("Enter a line of text followed by <enter>: ");

String str = reader.readline();

System.out.print("Enter an integer followed by <enter>: ");

int i = reader.readInt();

System.out.print("Enter a floating-point number followed by <enter>: ");

double d = reader.readDouble();

 

 


Text File Input with the Scanner Class

The Scanner class make text file input easy enough to use very early in a programming course. The scanner is opened on a text file rather than the keyboard, and the usual methods can be used for the input of different data types.  When used with a text file, a scanner behaves a bit like an iterator with collections. The method hasNext detects the end of the file, so a simple while loop can be used to read through a file of data. The following two code segments use scanners to read integers and strings from two text files and echo them to the terminal screen. The first code segment assumes that the integers in the file are separated by whitespace characters. The second code segment can process any text file:

 

import java.util.Scanner;
import java.io.File;

Scanner reader = new Scanner(new File("ints.txt"));
while (reader.hasNext()){
   int i = reader.nextInt();
   System.out.println(i);
}

reader = new Scanner(new File("lines.txt"));
while (reader.hasNext()){
   String str = reader.nextLine();
   System.out.println(str);
}