Java Reference
In-Depth Information
Display 2.7
Another Keyboard Input Demonstration (part 2 of 2)
Sample Dialogue
Enter two whole numbers
separated by one or more spaces:
42 43
You entered 42 and 43
Next enter two numbers.
A decimal point is OK.
9.99 57
You entered 9.99 and 57.0
Next enter two words:
jelly beans
You entered "jelly" and "beans"
Next enter a line of text:
Java flavored jelly beans are my favorite.
You entered "Java flavored jelly beans are my favorite."
The method next reads in a word, as illustrated by the following lines from Display 2.7:
String word1 = scannerObject.next();
String word2 = scannerObject.next();
If the input line is
jelly beans
then this will assign w1 the string "jelly" and w2 the string "beans" .
For the method next , a word is any string of nonwhitespace characters delimited by
whitespace characters such as blanks or the beginning or ending of a line.
If you want to read in an entire line, you would use the method nextLine . For
example,
word
String line = scannerObject.nextLine();
reads in one line of input and places the string that is read into the variable line .
The end of an input line is indicated by the escape sequence '\n' . This '\n'
character is what you input when you press the Enter (Return) key on the keyboard.
On the screen, it is indicated by the ending of one line and the beginning of the next
line. When nextLine reads a line of text, it reads this '\n' character, so the next
reading of input begins on the next line. However, the '\n' does not become part of
the string value returned. So, in the previous code, the string named by the variable
line does not end with the '\n' character.
These and other methods for reading in values from the keyboard are given in Display 2.8.
 
 
Search WWH ::




Custom Search