Java Reference
In-Depth Information
PITFALL: (continued)
There is nothing more on that line (except for '\n' ), so nextLine returns the empty
string. The second invocation of nextLine begins on the next line and reads "heads
are better than" .
When combining different methods for reading from the keyboard, you sometimes
have to include an extra invocation of nextLine to get rid of the end of a line (to get
rid of a '\n' ). This is illustrated in Display 2.7 .
The Empty String
A string can have any number of characters. For example, "Hello" has five characters.
There is a string with zero characters, which is called the empty string . The empty
string is written with a pair of double quotes, with nothing in between the quotes, like
so: "" . The empty string is encountered more often than you might think. If your code
is executing the nextLine method to read a line of text, and the user types nothing on
the line other than pressing the Enter (Return) key, then the nextLine method reads
the empty string.
empty string
TIP: Prompt for Input
Always prompt the user when your program needs the user to input some data, as in
the following example:
System.out.println("Enter the number of pods followed by");
System.out.println("the number of peas in a pod:");
TIP: Echo Input
You should normally echo input . That is, you should write to the screen all input
that your program receives from the keyboard. This way, the user can check that the
input has been entered correctly. For example, the following two statements from the
program in Display 2.9 echo the values that were read for the number of pods and the
number of peas per pod:
echo input
System.out.print(numberOfPods + " pods and ");
System.out.println(peasPerPod + " peas per pod.");
It might seem that there is no need to echo input, because the user's input is auto-
matically displayed on the screen as the user enters it. Why bother to write it to the
screen a second time? The input might be incorrect even though it looks correct. For
example, the user might type a comma instead of a decimal point or the letter O in
place of a zero. Echoing the input can expose such problems.
 
Search WWH ::




Custom Search