Section 6.8 Example: Data Validation
One frequent programming task is data validation. This task can take different forms depending on the nature of the program. One use for data validation occurs when accepting input from the user.
In the program in the preceding section, suppose the user types \(-10\) by mistake when asked to input an exam grade. Obviously this is not a valid exam grade and should not be added to the running total. How should a program handle this task?
Because it is possible that the user may take one or more attempts to correct an input problem, we should use a do-while structure for this problem. The program should first input a number from the user. The number should then be checked for validity. If it is valid, the loop should exit and the program should continue computing the before getting the input average grade. If it is not valid, the program should print an error message and input the number again. A flowchart for this algorithm is shown in Figure 6.8.1.
For example, suppose only numbers between 0 and 100 are considered valid. The data validation algorithm would be as follows:
do Get the next grade // Initialize: priming input if the grade < 0 or grade > 100 and grade != 9999 print an error message // Error case // Sentinel test while the grade < 0 or grade > 100 and grade != 9999
Note here that initialization and updating of the loop variable are performed by the same statement. This is acceptable because we must update the value of
grade on each iteration before checking its validity. Note also that for this problem the loop-entry condition is also used in the if statement to check for an error. This allows us to print an appropriate error message if the user makes an input error.
Let's incorporate this data validation algorithm into the
promptAndRead() method that we designed in the previous section (Listing 6.7.3). The revised method will handle and validate all input and return a number between 0 and 100 to the calling method. To reflect its expanded purpose, we will change the method's name to
getAndValidateGrade(), and incorporate it into a revised application, which we name
Activity 6.8.1. Validate.
Try this program below or online at Validate on repl.