// Fig. 3.6: AdditionApplet.java
// Roy's addition Java applet

// Java core packages
import java.text.DecimalFormat;
import java.awt.Graphics; // import class Graphics

// Java extension packages
import javax.swing.*; // import class JApplet

public class Average3 extends JApplet 
{
	//double sum; // sum of values entered by user
	
		//initialize applet by obtaining values from user
		public void init()
		{
			int gradeCounter, // number of grades entered
			gradeValue,	  // initialize the gradeValue
			total;	 	  // sum of the grades input by the user
			double average;	  // aveage of the grades
			String input; 	  // the string value entered
			
			// initialization phase
			total = 0;	// initialize total to zero
			gradeCounter = 0;	// initialize the counter to zero
			
			// Processing Phase
			// the instructions for input
			input = JOptionPane.showInputDialog( 
			"Start input of grades, to terminate enter -1" );
			
			// convert grade from a sString into an integer
			gradeValue = Integer.parseInt( input );
			
			// while loop control	
			while ( gradeValue != -1 )
				{
					// add grade value to the total
					total = total + gradeValue;
					
					// add 1 to gradeCounter
					gradeCounter = gradeCounter + 1;
					
					// prompt for next input and read grade from user
					input = JOptionPane.showInputDialog (
							 "Enter integer grade, -1 to Quit: " );
							 
					// convert grade from a String into an integer
					gradeValue = Integer.parseInt( input );
				} // end the while loop
				
			// termination phase
			DecimalFormat twoDigits = new DecimalFormat ( "0.00" );
			
			if ( gradeCounter != 0 )
				{
					average = (double) total / gradeCounter; // performs integer division
					
					// Display the average of exam grades
					JOptionPane.showMessageDialog( null,
					"Class average is: " + twoDigits.format ( average ),
					"Class average", JOptionPane.INFORMATION_MESSAGE );
					
					public void paint ( Graphics g ) 
					{
						// draw the results on applet's background
						// call inherited version of method paint
						super.paint(g);
						
						/* draw a rectangle starting from (15, 10) that is 300
						pixels wide and 20 pixels tall */
						g.drawRect( 15, 10, 300, 20 );
								
						// draw results as a string
						g.drawString( "The sum is " + average , 25, 25 );
							
					} // end method paint
					
				}
				else
					JOptionPane.showMessageDialog( null,
					"No grades were entered", "Class Average",
					JOptionPane.INFORMATION_MESSAGE );
			
			// Termination Phase
			System.exit( 0 ); // teminate the program
		}
			
} // end class AdditionApplet