/* * T01n21.java -- The object-oriented take on handling a collection of * scores. * * The collection of scores, and the operations that work on it, make a * nice object. Here, we define the class Scores that supports * the fetchScores(), computeAverage(), and computeSum() methods, along * with a constructor, a couple of getters, and a setter. * * I mixed in a lot of variety in how things get done. For instance, * sometimes methods call other methods to get values, etc., and other * times they do it themselves. In general, the calling approach is * best, to help isolate that specific task within one method; if that * task changes, we only have to change the implementation of that one * method. */ import java.util.*; class Scores { private int[] scores; // the scores held by the object private int numberOfScores; // the # of elements holding valid scores private int maxScores; // the quantity of scores we can store public Scores (int quantity) { scores = new int[quantity]; numberOfScores = 0; maxScores = quantity; } public int getScore(int index) { return scores[index]; } public void setScore(int index, int value) { scores[index] = value; } public int getQuantity() { return numberOfScores; } /* Note that fetchScores() references a Scanner object created * by the application program. This class doesn't know from * which source the scores will come from, so it shouldn't * be in charge of creating the Scanner object. The application * knows; let it worry about the source. */ public void fetchScores (Scanner keyboard) { numberOfScores = 0; // make sure we have an empty list do { System.out.print("Enter a score (-1 to quit): "); this.setScore(numberOfScores++,keyboard.nextInt()); } while (this.getQuantity() < maxScores && this.getScore(numberOfScores-1) != -1); if (this.getScore(numberOfScores-1) == -1) numberOfScores--; } public double computeAverage () { int total; // holds the sum of the scores total = this.computeSum(); return (double)total/numberOfScores; } public int computeSum () { int runningTotal = 0; // accumulates the sum for (int i = 0; i < numberOfScores; i++) { runningTotal += scores[i]; } return runningTotal; } } public class T01n21 { final static int MAX_SCORES = 10; public static void main (String [] args) { int numberOfScores, // quantity of scores entered by the user totalOfScores; // sum of the entered scores double average; // mean of the scores Scores collection; // reference to the object holding the scores Scanner keyboard = new Scanner (System.in); // source of user input collection = new Scores (MAX_SCORES); collection.fetchScores(keyboard); numberOfScores = collection.getQuantity(); totalOfScores = collection.computeSum(); average = collection.computeAverage(); if (numberOfScores > 0) { System.out.printf("\nThere are %d scores that total to %d;\n" + "the average for the class is %.2f.\n\n", numberOfScores, totalOfScores, average); } else { System.out.println("\nYou entered no scores; there is" + " no average.\n"); } } }