home *** CD-ROM | disk | FTP | other *** search
/ BURKS 2 / BURKS_AUG97.ISO / BURKS / LANGUAGE / JAVA / NOTES / SOURCE / guessing.jav < prev    next >
Text File  |  1996-12-20  |  2KB  |  60 lines

  1.  
  2. /* Simulation of console-I/O program GuessingGame,
  3.    using ConsoleApplet as a basis.  See the file
  4.    ConsoleApplet.java for more information.
  5.    
  6.    David Eck
  7.    eck@hws.edu
  8.    
  9.    August 11, 1996
  10. */
  11.  
  12. public class GuessingGameConsole extends ConsoleApplet {
  13.  
  14.    public void init() {
  15.       title = "Sample program \"GuessingGame\"";
  16.       super.init();
  17.    }
  18.  
  19.    protected void program() {
  20.    
  21.      /*  The user plays a guessing game where the
  22.          computer picks a number between 1 and 100,
  23.          and the user tries to guess the number
  24.      */
  25.      
  26.        console.putln("Let's play a game.  I'll pick a number between");
  27.        console.putln("1 and 100, and you try to guess it.");
  28.                       
  29.        boolean playAgain;
  30.                       
  31.        do {
  32.            playGame();  // call subroutine to play one game
  33.            console.put("Would you like to play again? ");
  34.            playAgain = console.getlnBoolean();
  35.        } while (playAgain);
  36.     
  37.     } // end program()
  38.     
  39.      
  40.     void playGame() {
  41.         int computersNumber = (int)(100 * Math.random()) + 1;
  42.               // The value assigned to computerNumber is a randomly
  43.               // chosen integer between 1 and 100, inclusive
  44.         int usersGuess; // this will be a number entered by user
  45.         console.putln();
  46.         console.put("What is your first guess? ");
  47.         do {
  48.             usersGuess = console.getInt();
  49.             if (usersGuess == computersNumber)
  50.                  console.putln("You got it!  My number was " + computersNumber);
  51.             else if (usersGuess < computersNumber)
  52.                   console.put("That's too low.  Try again: ");
  53.             else if (usersGuess > computersNumber)
  54.                   console.put("That's too high.  Try again: ");
  55.          } while (usersGuess != computersNumber);
  56.          console.putln();
  57.       } // end of playGame()
  58.  
  59. }  //end class GuessingGameConsole
  60.