/** ScoreArray.java -- find the max, min and median of a set of scores, * given on a line of input. * One interesting design question is this -- when should we call the * sort method? We basically have 3 choices: * 1. At the beginning of each of the 'find' methods. But this introduces * unnecessary waste. * 2. In the main() method in Driver. But this implementation detail * should be hidden from the other class. Why should main() be * responsible for sorting the array? Let's take care of it here. * 3. At the end of the constructor. That seems to be a good place. * In the future, we'll see that constructors sometimes have to do a * lot of work, and sometimes their work is delegated to other methods. */ import java.util.*; // for StringTokenizer import java.io.*; // for BufferedReader public class _______________ implements _______________ { private double [] score; public ScoreArray() throws IOException { System.out.println("Enter scores on one line:"); BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); String line = kbd.readLine(); StringTokenizer tok = new StringTokenizer(line, ", "); // First, go through the input line to count the values. // We do read tokens, but for now just ignore them. We just want // to know at this point how big the array should be. // (This step would not be necessary if we used an ArrayList.) int numValues = 0; while (tok.hasMoreTokens()) { ++numValues; String token = tok.nextToken(); } // Now we know how big the array should be. Initialize the array. score = new double[numValues]; tok = new StringTokenizer(line, ", "); for (int i = 0; i < numValues; ++i) score[i] = Double.parseDouble(tok.nextToken()); // Finally, sort the array. sort(); } /** sort the score array in descending order. Note the '<' in the * comparison. If we find two elements out of order, swap them. * This is not the most efficient sorting procedure, but it's simple to * remmeber. */ public void sort() { for (int i = 0; i < score.length; ++i) for (int j = i+1; j < score.length; ++j) if (score[i] < score[j]) { double temp = score[i]; score[i] = score[j]; score[j] = temp; } } public double findMax() { return score[0]; } /** findMedian -- If the number of elements is even, then we need to * average the 2 middle numbers. For example, if length = 6, we need * to average elements #2 and #3. If the length is odd, we just want * the one in the middle. If the length is 7, we want #3. */ public double findMedian() { if (score.length % 2 == 0) return (score[score.length / 2 - 1] + score[score.length / 2]) / 2; else return score[score.length / 2]; } }