/*
 *  File: Validate.java
 *  Author: Java, Java, Java
 *  Description: This class computes the average of an
 *    unlimited number of grades input by the user. The
 *    user terminates the input by typing the sentinel
 *    value 9999.
 */

import java.io.*;
public class Validate {

    private KeyboardReader reader = new KeyboardReader();  // Handles console input

    /**
     *  promptAndRead() handles all the input required by the program. It
     *   prompts the user and inputs a grade.
     *  @return a double representing the numeric grade input by the user
     *  Precondition: None
     *  Postcondition: A grade is returned
     */
    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))) // Input error
               System.out.println("Error: grade must be between 0 and 100 \n");  
            else
                System.out.println("You input " + grade + "\n");  // Confirm user input
        }  while ((grade != 9999) && ((grade < 0) || (grade > 100)));
        return grade;
    }

    /**
     *  inputAndAverageGrades() handles the program's main processing task.
     *   It repeatedly inputs a grade from the user, adding to the running
     *   total. When the input loop is exited, it calculates and returns the average.
     *  @return a double representing the computed average
     */
    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
    }
 
    /**
     *  main() -- Creates an instance of the Validate object to compute
     *   the average of the user's test grades.
     */
    public static void main(String argv[]) {
        System.out.println("This program calculates average grade."); // Explain program
        Validate avg = new Validate();
        double average = avg.inputAndValidateGrades();
        if (average == 0)                                             // Error case
            System.out.println("You didn't enter any grades.");
        else
            System.out.println("Your average is " + average);        
    } // main()
} // Validate
