Java Reference
In-Depth Information
called a
constructor
to set up the object. The
Scanner
constructor accepts a
parameter that indicates the source of the input. The
System.in
object represents
the
standard input stream
, which by default is the keyboard. Creating objects
using the new operator is discussed further in the next chapter.
Unless specified otherwise, a
Scanner
object assumes that white space charac-
ters (space characters, tabs, and new lines) are used to separate the elements of
the input, called
tokens
, from each other. These characters are called the input
delimiters
. The set of delimiters can be changed if the input tokens are separated
by characters other than white space.
The
next
method of the
Scanner
class reads the next input token as a string
and returns it. Therefore, if the input consisted of a series of words separated by
spaces, each call to
next
would return the next word. The
nextLine
method reads
all of the input until the end of the line is found, and returns it as one string.
The program
Echo
, shown in Listing 2.8, simply reads a line of text typed by the
user, stores it in a variable that holds a character string, then echoes it back to the screen.
The
import
statement above the definition of the
Echo
class tells the program
that we will be using the
Scanner
class in this program. The
Scanner
class is
part of the
java.util
class library. The use of the
import
statement is discussed
further in Chapter 3.
Various
Scanner
methods such as
nextInt
and
nextDouble
are provided to
read data of particular types. The
GasMileage
program, shown in Listing 2.9,
reads the number of miles traveled as an integer, and the number of gallons of
fuel consumed as a double, then computes the gas mileage.
LISTING 2.8
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class
Echo
{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void
main (String[] args)
Search WWH ::
Custom Search