/* COSC 304 section 2 LUKE BURGESS luke_burgess@hotmail.com @00205854 Oct 05 2000 */ // Lab task: Exercise 5.11, page 198 from "Java How To Program", Deitel & Deitel // Applet to read in integers from user and convert to rows of asterisks (a histogram) import javax.swing.JApplet; import javax.swing.JOptionPane; import java.awt.Graphics; public class Exercise11p198 extends JApplet { final int ARRAY_SIZE = 5; int currentInput, yPos; int [] array; String output; public void init () { array = new int [ARRAY_SIZE]; output = ""; yPos = 25; } public void paint (Graphics g) { // Validate user inputs, limit total number to that specified in ARRAY_SIZE, and build histogram for (int i = 0; i < ARRAY_SIZE; i++) { currentInput = askInt ("Enter integer (between 1 & 30):"); while ((currentInput < 1) || (currentInput > 30)) currentInput = askInt ("Invalid input. Re-enter integer (between 1 & 30):"); array [i] = currentInput; for (int j = 1; j <= array [i]; j++) output += "*"; g.drawString (output, 25, yPos); yPos += 10; output = ""; } // for() } // paint() public static String askLine (String prompt) { String userInput = JOptionPane.showInputDialog (prompt); return userInput == null ? "" : userInput; } public static int askInt (String prompt) { String userInput = askLine (prompt); try { return Integer.parseInt (userInput); } catch (NumberFormatException e) { return askInt ("Invalid input. Re-enter integer (between 1 & 30):"); } } } // class Exercise11p198