Page 172 - Introduction to Programming with Java: A Problem Solving Approach
P. 172
138 Chapter 4 Control Statements
condition is often considered to be elegant. For example, the above if conditions are more elegant than the
following functionally equivalent if conditions: if (inMotion == true)
{
if (upDirection == true)
{
.. .
The GarageDoor program is user-friendly because it requires a minimum amount of user input. A given user entry serves one of two purposes. The simplest kind of entry (pressing the Enter key) simulates push- ing the button on a garage door opener. Any other entry (not just a ‘q’ entry) terminates the looping process. Whenever a special data value (in this case anything except a plain Enter) tells a program to stop looping, we say we’re using a sentinel value to terminate the looping process. Because the program imposes a mini- mum burden on the user in terms of input, and because the code is relatively concise and efficient, it’s ap- propriate to call this an elegant implementation.
4.14 Input Validation
In the previous section, you learned to use a boolean variable to keep track of a two-way state. In this sec- tion, you’ll learn to use a boolean variable for a particularly common two-way state—the state of a user’s input in terms of whether it’s valid or invalid.
Input validation is when a program checks a user’s input to make sure it’s valid, that is, correct and reasonable. If it’s valid, the progrAampcaontginuoes. IfPitD’s iFnvalidE, tnhehpraognramceenters a loop that warns the user about the erroneous input and then prompts the user to re-enter.
In the GarageDoor program, note how the program checks for an empty string (which indicates the user wants to continue). If the string is not empty, it assumes that the user entered a ‘q’, but it doesn’t check specifically for a ‘q’. Consequently, it does not deal well with the possibility that the user accidentally hits another key before pressing the Enter key. It interprets that input as a quit command instead of a mistake.
To make the program more robust, you should provide input validation. There are several possible ways to do this. One of the simplest ways is to insert a while loop whose condition and’s together all bad pos- sibilities and whose body warns the user about the erroneous input and then prompts the user to re-enter. For the GarageDoor program in Figure 4.18, input validation is provided by the code fragment in Figure 4.19.
while (!entry.equals("") && !entry.equalsIgnoreCase("q"))
{
}
System.out.println("Invalid entry.");
System.out.print("Press Enter, or enter 'q': ");
entry = stdIn.nextLine();
Figure 4.19 Input validation loop to insert after the input statement in Figure 4.18
Where should you insert this code fragment? You want to validate the input right after the input is entered. So to make the GarageDoor program more robust, you should insert the above code fragment into Figure 4.18 immediately after this statement:
entry = stdIn.nextLine();