/* * File: Average.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 Average { private BufferedReader input = new BufferedReader // Handles console input (new InputStreamReader(System.in)); /** * convertStringTodouble() converts a String of the form "54.87" into * its corresponding double value (54.87). * @param s -- stores the string to be converted * @return A double is returned */ private double convertStringTodouble(String s) { Double doubleObject = Double.valueOf(s); return doubleObject.doubleValue(); } /** * getInput() handles all the input required by the program. It inputs * a grade as a String and converts it to double. * @return a double representing the numeric grade input by the user * Precondition: None * Postcondition: The result is a double value */ private double getInput() throws IOException { System.out.print("Input a grade (e.g., 85.3) "); System.out.print("or 9999 to indicate the end of the list >> "); String inputString = input.readLine(); double grade = convertStringTodouble(inputString); System.out.println("You input " + grade + "\n"); // Confirm user input 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() throws IOException { double runningTotal = 0; int count = 0; double grade = getInput(); // Initialize: priming input while (grade != 9999) { // Loop test: sentinel runningTotal += grade; count++; grade = getInput(); // Update: get next input } // 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 Average object to compute * the average of the user's test grades. */ public static void main(String argv[]) throws IOException { System.out.println("This program calculates average grade."); // Explain program Average avg = new Average(); double average = avg.inputAndAverageGrades(); if (average == 0) // Error case System.out.println("You didn't enter any grades."); else System.out.println("Your average is " + average); } // main() } // Average