Java Reference
In-Depth Information
Please enter a number:
No
You entered No
Not a number!
Please enter a number:
Yes
You entered Yes
Not a number!
Please enter a number:
42
You entered 42
BUILD SUCCESSFUL (total time: 11 seconds)
The first two inputs did not represent valid values in the
long
data type. The third
value was valid, and the run ended.
How It Works
Quite often our applications need to accept user input of some kind. Granted, most ap-
plications are not used from the command-line or terminal nowadays, but having the
ability to create an application that reads input from the command-line or terminal
helps to lay a good foundation, and may be useful in some applications. Terminal input
can also be useful in developing administrative applications that you or a system ad-
ministrator may use.
Two helper classes were used in the solution to this recipe. They are
java.io.BufferedReader
and
java.io.InputStreamReader
. The early
portion of the code that's using those classes is especially important to understand:
BufferedReader readIn = new BufferedReader(
new InputStreamReader(System.in)
);
The innermost object in this statement is
System.in
. It represents the keyboard.
You do not need to declare
System.in
. Java's runtime environment creates the ob-
ject for you. It is simply “there” to be used.
System.in
provides access to raw bytes of data from the input device, which is
the keyboard in our example. It is the job of the
InputStreamReader
class to take