// Exercise 5.11 Solution: Graphs.java // Program prints 5 histograms with lengths determined by user. // Java core packages import java.awt.Graphics; // Java extension packages import javax.swing.*; public class Graphs extends JApplet { int number1, number2, number3, number4, number5; // initialize applet by obtaining values from user public void init() { String inputString; int inputNumber, counter = 1; while ( counter <= 5) { inputString = JOptionPane.showInputDialog( "Enter number:" ); inputNumber = Integer.parseInt( inputString ); // define appropriate num if input is between 1-30 if ( inputNumber >= 1 && inputNumber <= 30 ) { switch ( counter ) { case 1: number1 = inputNumber; break; // done processing case case 2: number2 = inputNumber; break; // done processing case case 3: number3 = inputNumber; break; // done processing case case 4: number4 = inputNumber; break; // done processing case case 5: number5 = inputNumber; break; // done processing case } counter++; } // end if else JOptionPane.showMessageDialog( null, "Invalid Input\nNumber should be between 1 and 30", "Error", JOptionPane.ERROR_MESSAGE ); } // end while } // end method init // draw histograms on applet's background public void paint( Graphics g ) { // call inherited version of method paint super.paint( g ); int xCoordinate, yCoordinate = 0, value = 0; // print histograms for ( int counter = 1; counter <= 5; counter++ ) { switch ( counter ) { case 1: value = number1; break; // done processing case case 2: value = number2; break; // done processing case case 3: value = number3; break; // done processing case case 4: value = number4; break; // done processing case case 5: value = number5; break; // done processing case } xCoordinate = 5; yCoordinate = counter * 10 + 40; for ( int j = 1; j <= value; j++ ) g.drawString( "*", xCoordinate += 5, yCoordinate ); } } // end method paint } // end class Graphs