Wednesday, September 11, 2013

Number Guessing Game: Revisited

Today we made some changes to the Number Guessing Game:

// ======================
//  Number Guessing Game
//      Version 1.1
//   By Robert Griffith
// ======================
import java.util.Scanner;
  public class NumberGuessingGame2 {
        public static void main(String[] args)
        {
            int secretNumber;
            int guess;
            int tries;
            int maxtries;
           
            secretNumber = (int) (Math.random() * 999 + 1);
            //System.out.println("Secret number is " + secretNumber); // to be removed later
            Scanner keyboard = new Scanner(System.in);
            tries=0;
            maxtries=10;
                             
            do {
                tries=tries+1;
                System.out.print("Enter guess #" + tries + ": ");
                guess = keyboard.nextInt();
                System.out.println("Your guess is " + guess);
                if(tries > maxtries)
                   {
                   System.out.println("You have exceeded the maximum number of tries.  The secret number was " + secretNumber + ". Sorry!");
                   System.exit(0);
                   }
                if(guess == secretNumber)
                   {
                   System.out.println("Your guess is correct! It took you " + tries + " tries.  Congratulations!");
                   }
                if (guess < secretNumber)
                   {
                   System.out.println("Your guess is smaller than the secret number.");
                   }
                if (guess > secretNumber)
                   {
                   System.out.println("Your guess is larger than the secret number.");
                   }
            } while (guess != secretNumber);
        }
  }

No comments:

Post a Comment