Java Reference
In-Depth Information
EXAMPLE
int number;
number = keyboard.nextInt();
double cost;
cost = keyboard.nextDouble();
String word;
word = keyboard.next();
String line;
line = keyboard.nextLine();
PITFALL: Dealing with the Line Terminator, '\n'
The method nextLine of the class Scanner reads the remainder of a line of text start-
ing wherever the last keyboard reading left off . For example, suppose you create an
object of the class Scanner as follows:
Scanner keyboard = new Scanner(System.in);
and suppose you continue with the following code:
int n = keyboard.nextInt();
String s1 = keyboard.nextLine();
String s2 = keyboard.nextLine();
Now, assume that the input typed on the keyboard is:
2 heads are
better than
1 head.
This sets the value of the variable n to 2 , that of the variable s1 to " heads are" , and
that of the variable s2 to "better than" .
So far there are no problems, but suppose the input were instead
2
heads are better than
1 head.
You might expect the value of n to be set to 2 , the value of the variable s1 to
"heads are better than" , and that of the variable s2 to "1 head." . But that is not
what happens.
What actually happens is that the value of the variable n is set to 2 , that of the vari-
able s1 is set to the empty string, and that of the variable s2 to "heads are better
than" . The method nextInt reads the 2 but does not read the end-of-line character
'\n' . So the first nextLine invocation reads the rest of the line that contains the 2 .
(continued)
Search WWH ::




Custom Search