Java Reference
In-Depth Information
The following line creates an object of the class Scanner and names the object
keyboard :
Scanner keyboard = new Scanner(System.in);
After this line appears, you can use methods of the Scanner class with the object
keyboard to read data that the user types on the keyboard. For example, the method
nextInt reads one int value typed on the keyboard. So, the following line from
Display 2.6 reads one value of type int and makes that the value of the variable
numberOfPods :
nextInt
int numberOfPods = keyboard.nextInt();
In Display 2.6, two such statements each read one int value that the user types in
at the keyboard:
int numberOfPods = keyboard.nextInt();
int peasPerPod = keyboard.nextInt();
whitespace
The numbers typed in must be separated by whitespace , such as one or more spaces,
a line break, or other whitespace. Whitespace is any string of characters, such as blank
spaces, tabs, and line breaks, that prints as whitespace when written on (white) paper.
We often use the identifier keyboard for our Scanner object because the object
is being used for keyboard input. However, you may use other names. If you instead
want your object of the class Scanner to be named scannerObject , you would use the
following:
Scanner scannerObject = new Scanner(System.in);
To read a single int value from the keyboard and save it in the int variable n1 , you
would then use the following:
n1 = scannerObject.nextInt();
This is illustrated in the program in Display 2.7.
The program in Display 2.7 also illustrates some of the other Scanner methods for
reading values from the keyboard. The method nextDouble works in exactly the same
way as nextInt , except that it reads a value of type double . The following example is
from Display 2.7 :
nextDouble
double d1, d2;
d1 = scannerObject.nextDouble();
d2 = scannerObject.nextDouble();
System.out.println("You entered " + d1 + " and " + d2);
 
Search WWH ::




Custom Search