/* * T01n20.java -- Using an array, computes the sum and average of a group * of exam scores. Things to note: * * (1) Modular design (that is, use of appropriate methods and parameters) * * (2) A demonstration (in the method fetchScores) of passing in an * existing array and populating it. The following example program * shows a different approach. * * Notice that main() and computeAverage() both call computeSum(). Yes, * this means that we are wasting time computing the sum twice, but it's * also logical; when some part of the program needs the sum, it calls * computeSum() to get it. There are some tricks we could play to get * the sum just once for both uses, but it's clearer the way it is. * (Remember, for most programming, you'd rather sacrifice a little efficiency * for an understandable, reliable solution (and thus easier maintenance). */ import java.util.*; public class T01n20 { 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 int[] scores; // the collection of scores scores = new int[MAX_SCORES]; numberOfScores = fetchScores(scores); totalOfScores = computeSum(scores,numberOfScores); average = computeAverage(scores,numberOfScores); 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"); } } private static int fetchScores (int[] list) { int numberOfScores = 0; // Haven't seen any scores yet Scanner keyboard = new Scanner (System.in); // source of user input // Continue accepting scores until the array is full // or the user enters -1. Note that we're changing the // content of the array, which is the same array that main() // created. Thus, no need to return the array. do { System.out.print("Enter a score (-1 to quit): "); list[numberOfScores++] = keyboard.nextInt(); } while (numberOfScores < MAX_SCORES && list[numberOfScores-1] != -1); // Adjust the quantity of scores stored if -1 was entered if (list[numberOfScores-1] == -1) numberOfScores--; return numberOfScores; } private static double computeAverage (int[] list, int quantity) { int total; // holds the sum of the scores total = computeSum(list,quantity); return (double)total/quantity; } private static int computeSum (int[] list, int quantity) { int runningTotal = 0; // accumulates the sum for (int i = 0; i < quantity; i++) { runningTotal += list[i]; } return runningTotal; } }