Java Reference
In-Depth Information
Console Input
Responses typed by the user when an interactive program pauses for input.
When you refer to System.out , you are accessing an object in the System class
known as the standard output stream, or “standard out” for short. There is a corresponding
object for standard input known as System.in , but Java wasn't designed for console
input, and System.in has never been particularly easy to use for this purpose. Fortu-
nately for us, there is an easier way to read console input: Scanner objects.
Most objects have to be explicitly constructed by calling a special method known as a
constructor.
Constructor (Construct)
A method that creates and initializes an object. Objects in Java programs
must be constructed before they can be used.
Remember that a class is like a blueprint for a family of objects. Calling a construc-
tor is like sending an order to the factory asking it to follow the blueprint to get you an
actual object that you can manipulate. When you send in your order to the factory, you
sometimes specify certain parameters (e.g., what color you want the object to be).
In Java, constructors are called using the special keyword new , followed by the
object's type and any necessary parameters. For example, to construct a specific Scanner
object, you have to pass information about the source of input. In particular, you have to
provide an input stream. To read from the console window, pass it System.in :
Scanner console = new Scanner(System.in);
Once you've constructed the Scanner , you can ask it to return a value of a partic-
ular type. A number of methods, all beginning with the word “next,” are available to
obtain the various types of values. Table 3.4 lists them.
Typically, you will use variables to keep track of the values returned by these
methods. For example, you might say:
int n = console.nextInt();
The call on the console object's nextInt method pauses for user input. Whenever
the computer pauses for input, it will pause for an entire line of input. In other words, it
will wait until the user hits the Enter key before continuing to execute the program.
Table 3.4
Scanner Methods
Method
Description
reads and returns the next token as a String
next()
reads and returns a double value
nextDouble()
reads and returns an int value
nextInt()
reads and returns the next line of input as a String
nextLine()
 
 
Search WWH ::




Custom Search