// guessNum.java // Guess a number until you get it right // Java packages import java.awt.Graphics; // import class Graphics import java.awt.Color; // import class Color import javax.swing.*; // import package javax.swing public class guessNum extends JApplet { int theNum; // the answer // initialize applet by getting a random number // the method start is called every time the browser page is refreshed public void start() { double tempNum; // create the correct answer tempNum = Math.random( ); tempNum *= 10; theNum = (int) tempNum; } // end method start // draw results in a rectangle on appletís background public void paint( Graphics g ) { // call superclass version of method paint super.paint( g ); String strGuess; int theGuess; strGuess = JOptionPane.showInputDialog( "Enter an integer" ); theGuess = Integer.parseInt( strGuess ); // draw rectangle starting from (15, 10) that is 270 // pixels wide and 20 pixels tall g.setColor(Color.RED); g.drawRect( 15, 10, 270, 20 ); while (theGuess != theNum && theGuess != -1){ // draw results as a String at (25, 25) g.drawString( "Sorry! Try again! " + theNum, 25, 25 ); strGuess = JOptionPane.showInputDialog( "Enter an integer" ); theGuess = Integer.parseInt( strGuess ); } // end while g.clearRect( 15, 10, 270, 20 ); if (theGuess == theNum){ g.drawString( "You win! The correct number is ", 25, 25 ); g.drawString( strGuess, 100, 50 ); } else { g.drawString( "You gave up! The correct number is ", 25, 25 ); g.drawString( "" + theNum, 100, 50 ); } } // end method paint } // end class guessNum