Section 2.6. From the Java Library: java.util.Scanner


[Page 91 (continued)]

2.6. From the Java Library: java.util.Scanner

IF WE WISH to write useful interactive programs, we must be able to receive information from users as well as send information to them. We saw in the preceding chapter that output from a program can be sent to the console window by simply using the System.out.print() and System.out.println() statements. In this section we describe two simple ways that Java can handle keyboard input. Receiving input from the keyboard, together with sending output to the console window, creates one of the standard user interfaces for programs.

java.sun.com/docs


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. Getting keyboard input from System.in involves two complications that are not present in dealing with System.out.println(). First, the normal keyboard input data requested of a user consists of a sequence of characters or digits that represent a word, phrase, integer, or real number. Normally, an entire sequence of characters typed by the user will represent data to be stored in a single variable, with the user hitting the return or enter key to signal the end of a piece of requested data. Java has a special class, Buffered Reader, that uses an input stream and has a method that collects characters until it reads the character or characters that correspond to hitting the return or enter key. A second complication for reading input involves the problem of how to handle receiving data that is not in the same format as expected. The BufferedReader class handles this problem by using certain exceptions, a special kind of error message that must be handled by the programmer. Chapter 10 is devoted to exceptions, and we will avoid their use, as far as possible, until that time.

There is an alternative way to handle keyboard input in the Java 2 Platform Standard Edition 5.0 (J2SE 5.0). A Scanner class has been added to the java.util package which permits keyboard input without forcing the programmer to handle exceptions. We introduce the Scanner class in the next subsection and then describe how a user-defined class introduced in Chapter 4 can function in an equivalent fashion to permit simple keyboard input.

2.6.1. Keyboard Input with the Scanner Class

A partial definition of Scanner is shown in Figure 2.25. Note that the Scanner methods listed are but a small subset of the public methods of this class. The Scanner class is in the java.util package, so classes that use it should import it with the following statement:

import java.util.Scanner; 



[Page 92]

Figure 2.25. The Scanner class, with a partial list of its public methods.


The Scanner class is designed to be a very flexible way to recognize chunks of data that fit specified patterns from any input stream. To use the Scanner class for keyboard input, we must create a Scanner instance and associate it with System.in. The class has a constructor for this purpose, so the statement

Scanner sc = new Scanner(System.in); 


declares and instantiates an object that can be used for keyboard input. After we create a Scanner object, we can make a call to nextInt(), nextdouble(), or next() to read, respectively, an integer, real number, or string from the keyboard. The program in Figure 2.26 demonstrates how an integer would be read and used. When the nextInt() method is executed, no further statements are executed until an int value is returned by the method. 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 output

Input an integer: 


Figure 2.26. A very brief program with a Scanner object used for keyboard input.

import java.util.Scanner; public class TestScanner {   public static void main(String[] args)   {                                                      // Create Scanner object     Scanner sc = new Scanner(System.in);     System.out.print("Input an integer:");               // Prompt     int num = sc.nextInt();                              // Read an integer     System.out.println(num + " squared = " + num*num);   } // main() } // TestScanner class 

to the console window, and the program will wait for the user to type in an integer and hit the return or enter key. After this has been done the output will look something like:

Input an integer:123 123 squared = 15129 



[Page 93]

Keyboard input of real numbers and strings is 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 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.

Since the Scanner class is designed as a flexible tool for recognizing chunks of data from any input stream, it has some properties that may be unexpected and not totally compatible with simple keyboard input. A Scanner object has a set of character strings that separate, or delimit, the chunks of data it is looking for. By default, this set of delimiters consists of any nonempty sequence of white space characters, that is, the space, tab, return, and newline characters. This will allow a user to input several integers separated by spaces before hitting the enter key. This might be handled by code like:

System.out.print("Input two integers and an enter:"); int num1 = sc.nextInt(); int num2 = sc.nextInt(); 


White space as delimiters also means that the next() method cannot return an empty string, nor can it return a string that contains any spaces. For example, consider the code:

System.out.print("Input the first president of the USA:"); String str = sc.next(); 


If one types "George Washington" and hits the enter key, the string str will store only "George." In order to get a Scanner object to read strings that contain spaces, we must use the useDelimiter() method to define the set of delimiters as just that character string generated by hitting the enter key. For example, for some Windows operating systems, the statement

sc = sc.useDelimiter("\r\n"); 


will result in the next() method returning the entire string of characters input from the keyboard, up to but not including those generated by hitting the enter key.


[Page 94]

The fact that we can use a Scanner object to write Java code that ignores exceptions does not mean that exceptions will not be generated by keyboard input. If the user enters letters rather than digits for the nextInt() method to process, the program will be terminated with an error message.

It must be stressed that the strategy for handling keyboard input outlined above is a temporary strategy until the topic of exceptions is covered in Chapter 11. Real software applications that use keyboard input should carefully handle the possibility that a user will enter something unexpected. In Java, this can only be done by handling exceptions.

2.6.2. Keyboard Input with the KeyboardReader Class

If you are using an older version of Java that does not have the Scanner class, a user-defined class can be used instead. A KeyboardReader class that uses the BufferedReader class will be developed in Chapter 4. It has methods that read data from the keyboard in a manner very similar to those of the Scanner class. A partial list of its public methods is given in the UML class diagram shown in Figure 2.27. To use the KeyboardReader class for keyboard input, copy the source code KeyboardReader.java from Chapter 4 into the same directory as the source code of your current Java class (and add it to your current project if you are using a integrated development environment).

Figure 2.27. A UML class diagram of the KeyboardReader class.


To use a KeyboardReader object, we need to create an instance of the class with a constructor. Then calling one of the three methods will return an int, double, or String when data is input from the keyboard. Any of the three methods of a KeyboardReader object will attempt to process the entire string input from the keyboard up to the point that the enter key is hit. That is, the character or characters generated by hitting the return or enter key are the delimiters used by KeyboardReader. The TestKeyboardReader class definition in Figure 2.28 reads an integer from the keyboard and squares it just like the TestScanner class. In the remainder of the text, any time the Scanner class is used for keyboard input, the same program can be run using the KeyboardReader class after making the obvious substitutions.

Figure 2.28. A very brief program with a KeyboardReader object used for keyboard input.

public class TestKeyboardReader {   public static void main(String[] args)   {                                            // Create KeyboardReader object     KeyboardReader kb = new KeyboardReader();     System.out.print("Input an integer:");     // Prompt     int num = kb.getKeyboardInteger();         // Read an integer     System.out.println(num + " squared = " + num*num);   } // main() } // TestKeyboardReader class 


[Page 95]
Self-Study Exercise

Exercise 2.8

Modify the main() method of the TestScanner class so that it reads a real number from the keyboard rather than an integer.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net