Java Reference
In-Depth Information
Not all variables are initialized during declaration. The nature of the program or
the programmer's choice dictates which variables should be initialized during
declaration.
Input (Read) Statement
In an earlier section, you learned how to put data into variables using the assignment
statement. In this section, you will learn how to put data into variables from the standard
input device using Java's input (or read) statements.
In most cases, the standard input device is the keyboard.
When the computer gets the data from the keyboard, the user is said to be acting
interactively.
READING DATA USING THE Scanner class
To put data into variables from the standard input device, Java provides the class
Scanner. Using this class, we first create an input stream object and associate it with
the standard input device. The following statement accomplishes this:
static Scanner console = new Scanner(System.in);
This statement creates the input stream object console and associates it with the standard
input device. (Note that Scanner is a predefined Java class and the preceding statement creates
console to be an object of this class.) The object console reads the next input as follows:
a.
If the next input token can be interpreted as an integer, then the expression:
console.nextInt()
retrieves that integer; that is, the value of this expression is that integer.
b. If the next input token can be interpreted as a floating-point number, then
the expression:
console.nextDouble()
retrieves that floating-point number; that is, the value of this expression
is that floating-point number. (Note that an integer can be treated as a
floating-point number with 0 decimal part.)
c. The expression:
console.next()
retrieves the next input token as a string; that is, the value of this
expression is the next input string. (Note that if the next input token is a
number, this expression interprets that number as a string.)
 
 
 
Search WWH ::




Custom Search