9. Control Structures

9.8. Example: Data Validation

One frequent programming task is data validation. This task can take dif- ferent 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.11.

For example, suppose only numbers between 0 and 100 are considered valid. The data validation algorithm would be as follows:

,,

 

 

 

 

 

J

Note here that initialization and updating of the loop variable are per-

formed by the same statement. This is acceptable because we must up-

date the value of grade on each iteration before checking its validity. Note

 

Figure 6.11: Do-while is a good structure for the data validation algorithm.


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 promptAnd- Read() method that we designed in the previous section (Fig. 6.10). 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 pur- pose, we will change the method’s name to getAndValidateGrade(), and incorporate it into a revised application, which we name Validate (Fig. 6.12).