Section 6.8. Example: Data Validation


[Page 275 (continued)]

6.8. Example: Data Validation

A 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.


[Page 276]

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 make 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 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.

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


Algorithm design


For example, suppose only numbers between 0 and 100 are considered valid. The datavalidation 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 while the grade < 0 or grade > 100 and grade != 9999 // Sentinel test 


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 preceding 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 purpose, we will change the method's name to getAndValidateGrade(), and incorporate it into a revised application, which we name Validate (Fig. 6.12).


[Page 277]

Figure 6.12. A program to compute average grade using a while structure. This version validates the user's input.

import java.io.*; public class Validate {                                  // Console input   private KeyboardReader reader = new KeyboardReader();   private double getAndValidateGrade() {     double grade = 0;     do {        reader.prompt("Input a grade (e.g., 85.3) " +                      "or 9999 to indicate the end of the list >> ");        grade = reader.getKeyboardDouble();        if ((grade != 9999) && ((grade < 0) || (grade > 100))) // If error           System.out.println("Error: grade must be between 0 and 100 \n");        else           System.out.println("You input " + grade + "\n");  // Confirm input     }  while ((grade != 9999) && ((grade < 0) || (grade > 100)));     return grade;   }   public double inputAndAverageGrades() {     double runningTotal = 0;     int count = 0;     double grade = getAndValidateGrade();       // Initialize: priming input     while (grade != 9999) {                     // Loop test: sentinel        runningTotal += grade;        count++;        grade = getAndValidateGrade();           // Update: get next grade     }                                           // while     if (count > 0)                              // Guard against divide-by-zero        return runningTotal / count;             // Return the average     else      return 0;                                  // Special (error) return value   }   public static void main(String argv[]) {     System.out.println("This program calculates average grade."); // Explain     Average avg = new Average();     double average = avg.inputAndAverageGrades();     if (average == 0)                          // Error check        System.out.println("You didn't enter any grades.");     else        System.out.println("Your average is " + average);   } // main() } // Validate class 




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net