The Scanner class allows the client to scan text to identify primitive types (like boolean, int, double and so on) and Strings. You should have already used the Scanner class for eCheck 03C to read numeric input from a user.
A Scanner object is often used
to retrieve keyboard input from the user. The
Scanner works by separating
its input text into chunks called tokens where
the tokens are separated by whitespace. For example, the
string:
"1 fish 2 fish red fish blue fish"
has 8 tokens (two integers and six strings) separated by spaces.
A client can retrieve the tokens from a Scanner object
by asking for specific types of tokens in the correct order.
For example, in this case the user could ask for in order:
integer, string, integer, string, string, string, string, string
or
real number, string, real number, string, string, string, string, string
or
string, string, string, string, string, string, string, string
The numbers 1 and 2 can be interpreted as integers, real numbers, or strings depending on the application.
Use the techniques you learned from the previous labs to create a suitable directory for this lab and start jEdit. You might consider opening a terminal and entering the following commands:
cd Documents/cse1020
mkdir lab04
cd lab04
jedit &
The following program asks for and reads some specific types of inputs from the user. The program does not do much, but some explanation might be helpful:
Line 9: A Scanner object named in is created using a constructor that accepts System.in as an argument. System.in refers to the standard input stream, which is typically the keyboard input for a desktop computer. The Scanner object referred to by in will scan the stream of characters coming from the keyboard.
Line 12: We ask in for the next boolean value. The Scanner object will scan the keyboard input and try to interpret the input as a boolean value.
Line 15: We ask in for the next int value. The Scanner object will scan the keyboard input and try to interpret the input as an int value.
Line 18: We ask in for the next double value. The Scanner object will scan the keyboard input and try to interpret the input as a double value.
Line 24-25: We use the PrintStream
method printf to concisely output
the scanned values. Recall that:
%n substitutes a newline character
%d substitutes an integer value
%f substitutes a floating-point value
%s substitutes a string
Create, save, compile, and run the ScannerInput program. After running the program successfully, try the following and observe the behaviour of the Scanner object:
When you are satisfied that you know how to use a Scanner object to get input from a user you may