/**
 *  File: Data.java
 *
 *  Contains the data to be used by AddEmUp
 *  and the methods that process this data, including I/O.
 *
 *  Author: Bary W Pollack
 *  Date:   Jan. 7, 2007
**/

import java.util.Arrays;		// for the sort() method
import java.util.Scanner;		// for the nextDouble() method

/**
 *  The Data class contains the data to be used by AddEmUp
 *  and the methods for processing the data
**/
class Data {

	// Constructor: set up data storage
	Data() {
		nCount = 0;
		dAverage = -1.0;
		dValues = new double[MAX_NUMBER];
	}


	// Accessor methods
	public int getCount() { return nCount; }
	public double getAverage() { return dAverage; }
	public double getValue(int j) { return dValues[j]; }


	// input() acquires the data to be used by this program
	// from the keyboard; a values <= 0 terminates input
	public void input() {
		double dValue;
		Scanner scanner = new Scanner(System.in);

		// loop until a value <= 0 is read
		for (;;) {
			System.out.print("Value(s): ");
			dValue = scanner.nextDouble();
			// stop the input process if you see a value <= 0
			if (dValue <= 0)
				break;
			insert(dValue);
		}
	} // end input()


	// insert() inserts one new item in the array
	public void insert(double dValue) {
		if (nCount < dValues.length) {
			// insert the value into the array; increase the count
			dValues[nCount++] = dValue;
		} else {
			System.err.println("\nArray capacity reached (" + MAX_NUMBER + ")");
			java.awt.Toolkit.getDefaultToolkit().beep();
		}
	} // end insert()


	// calculate() finds the average of the acquired data
	public void calculate() {
		double dSum = 0.0;
		for (int i = 0; i < nCount; i++)
			dSum += dValues[i];
		dAverage = (nCount > 0) ? dSum / nCount : 0.0;
	} // end calculate()


	// display() just displays the contents of the array on the screen
	// If the average is >= 0, then it is displayed as well
	public void display(String sTitle) {
		System.out.print("\n" + sTitle);
		for (int i = 0; i < nCount; i++)
			System.out.print(" " + dValues[i]);
		System.out.println();
		// display the average when appropriate
		if (dAverage >= 0)
			System.out.printf("Average of %d values is %.2f\n", nCount, dAverage);
	} // end display()


	// sort() just uses the Arrays.sort method;
	// but it could implement a bubble sort or any other kind of sort
	public void sort() {
		Arrays.sort(dValues, 0, nCount);
	} // end sort()


	// data storage for Data
	public final static int MAX_NUMBER = 15;	// maximum number of values
	private double[] dValues;					// array of values
	private double dAverage;					// average of the values
	private int nCount;							// current length of array

} // end class Data
