// DoubleArray.java
// Demos working with a two-dimensional array of sales data
// Prints sales array
// Computes sales per rep and sales per month and totals
import java.awt.*;
import java.text.DecimalFormat;
import java.awt.event.*;
import javax.swing.*;

public class DoubleArray extends JApplet implements ActionListener {
	// hard-coded two-dimensional sales array
	// array is 4 reps x 6 months
	int sales[ ] [ ] = { { 50, 60, 45, 50, 80, 70 }, {110, 120, 120, 100, 80, 120 }, { 70, 80, 90, 200, 85, 85 }, { 30, 10, 30, 80, 70, 80 } };
	int reps, months;
	int repSales[ ];  // sales of each rep
	int monSales[ ];  // sales per month

	// GUI Components
	Container c;
	JTextArea outputArea;
	JButton b;

	DecimalFormat twoDigits;

	public void init( ) {
		// initialize instance variables for clarity
		reps = sales.length;
		months = sales[ 0 ].length;

		repSales = new int[ reps ];
		monSales = new int[ months ];

		// GUI Components
		c = getContentPane( );
		c.setLayout( new FlowLayout( ) );
		outputArea = new JTextArea( 20, 60 );
		c.add( outputArea );
		b = new JButton( "Compute" );
		b.addActionListener( this );
		c.add( b );

		twoDigits = new DecimalFormat( "0.00" );  // format averages to two decimal places
	}

	public void actionPerformed( ActionEvent e ) {
		// initialize outputArea
		outputArea.setText( "" );

		// do all computations before any printing

		// Fill repSales array with totals
		for ( int r = 0; r < reps; r++ )
			for ( int m = 0; m < months; m++ ) 
				repSales[ r ] += sales[ r ][ m ];

		// Fill monSales array with totals
		for ( int m = 0; m < months; m++ )
			for ( int r = 0; r < reps; r++ )
				monSales[ m ] += sales[ r][ m ];

		// Compute grand total
		int grandTotal = 0;
		for ( int r = 0; r < reps; r++ ) 
			grandTotal += repSales[ r ];
		
		// print table title
		outputArea.append( "SALES DATA -- FALCINELLI, INC.\n" );

		for ( int m = 0; m < months; m++ )
			outputArea.append( "\tMon " + ( m + 1 ) );
		
		outputArea.append( "\tTotal\n" );

		// print the array
		for ( int r = 0; r < reps; r++ ) {
			outputArea.append( "\nRep " + ( r + 1 ) + "\t" );
			for ( int m = 0; m < months; m++ )
				outputArea.append( String.valueOf( sales[ r ][ m ] ) + "\t" );
			outputArea.append( String.valueOf( repSales[ r ] ) + "\t" );
		}
		
		// Print monthly totals
		outputArea.append( "\n\nTotal\t" );
		for ( int m = 0; m < months; m++ )
			outputArea.append( String.valueOf( monSales[ m ] ) + "\t" );

		outputArea.append( String.valueOf( grandTotal ) );

		// Compute and print average sales per rep and per month
		// Explicit cast is needed to convert integer grandTotal to a double
		outputArea.append( "\n\nAverage sales per rep:  " + twoDigits.format( ( double ) grandTotal / reps ) );
		outputArea.append( "\n\nAverage sales per month:  " + twoDigits.format( ( double ) grandTotal / months ) );
	}
}