Java Reference
In-Depth Information
Handling User Errors
Consider the following code fragment:
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
int age = console.nextInt();
What if the user types something that is not an integer? If that happens, the
Scanner will throw an exception on the call to nextInt . We saw in the previous sec-
tion that we can test whether or not the next token can be interpreted as an integer by
using the hasNextInt method. So, we can test before reading an int whether the
user has typed an appropriate value.
If the user types something other than an integer, we want to discard the input,
print out some kind of error message, and prompt for a second input. We want this
code to execute in a loop so that we keep discarding input and generating error mes-
sages as necessary until the user enters legal input.
Here is a first attempt at a solution in pseudocode:
while (user hasn't given us an integer) {
prompt.
discard input.
generate an error message.
}
read the integer.
This reflects what we want to do, in general. We want to keep prompting, discard-
ing, and generating error messages as long as the input is illegal, and when a legal
value is entered, we want to read the integer. Of course, in that final case we don't
want to discard the input or generate an error message. In other words, the last time
through the loop we want to do just the first of these three steps (prompting, but not
discarding and not generating an error message). This is another classic fencepost
problem, and we can solve it in the usual way by putting the initial prompt before the
loop and changing the order of the operations within the loop:
prompt.
while (user hasn't given us an integer) {
discard input.
generate an error message.
prompt.
}
read the integer.
 
Search WWH ::




Custom Search