Java Reference
In-Depth Information
much attention was given to reading keyboard input. It was assumed that all
programmers would produce graphical user interfaces with text fields and menus.
System.in
was given a minimal set of featuresȌit can only read one byte at a
time. Finally, in Java version 5, a
Scanner
class was added that lets you read
keyboard input in a convenient manner.
To construct a
Scanner
object, simply pass the
System.in
object to the
Scanner
constructor:
Scanner in = new Scanner(System.in);
You can create a scanner out of any input stream (such as a file), but you will usually
want to use a scanner to read keyboard input from
System.in
.
Once you have a scanner, you use the
nextInt
or
nextDouble
methods to read
the next integer or floating-point number.
System.out.print("Enter quantity: ");
int quantity = in.nextInt();
System.out.print("Enter price: ");
double price = in.nextDouble();
When the
nextInt
or
nextDouble
method is called, the program waits until the
user types a number and hits the Enter key. You should always provide instructions
for the user (such as
ÐEnter quantity:Ñ
) before calling a
Scanner
method.
Such an instruction is called a prompt.
The
nextLine
method returns the next line of input (until the user hits the Enter
key) as a
String
object. The next method returns the next word, terminated by any
white space, that is, a space, the end of a line, or a tab.
System.out.print("Enter city: ");
String city = in.nextLine();
System.out.print("Enter state code: ");
String state = in.next();
Here, we use the
nextLine
method to read a city name that may consist of multiple
words, such as
San Francisco
. We use the
next
method to read the state code
(such as
CA
), which consists of a single word.
165