Activity 6.8.1. Validate.
Try this program below or online at Validate on repl.
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
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.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
while
structure. This version validates the user’s input.