Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

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
Figure 6.8.1. Flow Chart for Data Validation Algorithm structure.
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 Validate(Listing 6.8.2).
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
Listing 6.8.2. A program to compute average grade using a while structure. This version validates the user’s input.

Activity 6.8.1. Validate.

Try this program below or online at Validate on repl.
You have attempted of activities on this page.