Section2.7From the Java Library: java.util.Scanner
If we wish to write useful interactive programs, we need to send and receive information to and from the user. In the previous chapter, we learned how to send output from a program to the console using the System.out.print() and System.out.println() statements.
In this section we introduce the java.util.Scanner class for handling keyboard input.
Recall that in Java any source or destination for I/O is considered a stream of bytes or characters. To perform keyboard input, we will extract characters from System.in, the input stream connected to the keyboard.
Subsection2.7.1Keyboard Input with the ScannerClass
A partial definition of Scanner is shown in Figure 2.7.1. The methods listed there are but a small subset of the public methods of this class. Because the Scanner class is in the java.util package we need to import it as follows when we want to use it:
import java.util.Scanner;
To use a Scanner object for keyboard input, we must create an instance and associate it with System.in. The following statement will declare and instantiate an object that can be used for keyboard input:
Scanner sc = new Scanner(System.in);
After we create a Scanner object, we can make a call to nextInt(), nextDouble(), or next(), depending on the type of input data we want — an integer, a real number, or a string. The program in Listing 2.7.2 demonstrates how an integer would be read and used.
When the nextInt() method is called, no further statements are executed until an int value is read from the keyboard and assigned to num. Normally this does not happen until the user has typed in the digits of an integer and hit the return or enter key. Thus executing the main() method of the TestScanner class will result in the following interaction:
Input an integer:123
123 squared = 15129
Keyboard input of real numbers and strings would be handled in a similar manner.
Keyboard input will allow us to create examples of command line interfaces for interactive programs. For example, the code
Scanner sc = new Scanner(System.in);
Riddle riddle = new Riddle(
"What is black and white and red all over?",
"An embarrassed zebra.");
System.out.println("Here is a riddle:");
System.out.println(riddle.getQuestion());
System.out.print("To see the answer, "); // Prompt
System.out.println("type a letter and enter.");
String str = sc.next(); // Wait for input
System.out.println(riddle.getAnswer());
will display a riddle question and prompt the user to type a letter and to hit the enter key to see the answer. In the next chapter, we will develop new methods for the OneRowNim class that will be able to use int values input from the keyboard for the next move.
Subsection2.7.2Scanner Peculiarities
The Scanner class is designed to work with a wide variety of input streams, not just keyboard input. Because of this, it has some features that don’t work well with simple keyboard input.
One such peculiarity is that by default a Scanner object assumes that individual chunks of data are separated by (or, delimited by) white space — i.e., by blank spaces or tabs or carriage returns or new lines. This poses a problem when using a Scanner to read a string that contains spaces. For example, consider the following code segment:
System.out.print("Input the name of the first president of the USA:");
String str = sc.next();
If you type "George Washington" and hit the enter key, the string str will store only "George", because the Scanner will stop inputting when it encounters the blank space.
In order to get a Scanner object to read strings that contain spaces, we must call the useDelimiter() method to tell Scanner to include only carriage returns and enter keys as its delimiters. For example, the following statement, which works on most Windows systems,
sc = sc.useDelimiter("\r\n");
will enable the next() method to input strings that contain spaces. It will accept all keyboard input up to but not including the enter key. (The “\r” and “\n” are the ASCII characters for carriage return and new line, respectively.)
Subsection2.7.3Exceptions
There are lots of things that csn go wrong when performing input. For example, if your program calls nextInt() to input an integer and the user types “hello”, the program will be terminated with an error message.
Generally, Java programs use Exceptions to handle such situations. We deliberately chose the Scanner class because it doesn’t require us to deal with exceptions right now. We’ll cover that topic in chapter 11.
But it’s important to realize that our strategy for handling keyboard input with the Scanner class is a temporary solution.
ExercisesSelf-Study Exercise
1.TestScanner for Decimals.
Modify the main() method of the TestScanner class (Listing 2.7.2) so that it reads a real number (a decimal number) from the keyboard rather than an integer. You will need to test this in a development environment that allows user input.