Posted by : Unknown Friday, 19 June 2015


import java.util.Scanner;
public class GuessingGame {
    public static void main(String[] args) {
        System.out.println("Let's play a game.  I'll pick a number between");
        System.out.println("1 and 100, and you try to guess it.");
        playGame(); 
        System.out.println("Thanks for playing.  Goodbye.");
    } // end of main()    
    static void playGame() {
        Scanner input = new Scanner( System.in );
        int computersNumber; // A random number picked by the computer.
        int usersGuess;      // A number entered by user as a guess.
        int guessCount;      // Number of guesses the user has made.
        computersNumber = (int)(100 * Math.random()) + 1;           
        guessCount = 0;
        System.out.println();
        System.out.print("What is your first guess? ");
        while (true) {
            usersGuess = input.nextInt();  // Get the user's guess.
            guessCount++;
            if (usersGuess == computersNumber) {
                System.out.println("You got it in " + guessCount
                        + " guesses!  My number was " + computersNumber);
                break;  // The game is over; the user has won.
            }
            if (guessCount == 6) {
                System.out.println("You didn't get the number in 6 guesses.");
                System.out.println("You lose.  My number was " + computersNumber);
                break;  // The game is over; the user has lost.
            }           
            if (usersGuess < computersNumber)
                System.out.print("That's too low.  Try again: ");
            else if (usersGuess > computersNumber)
                System.out.print("That's too high.  Try again: ");
        }
        System.out.println();
    } // end of playGame()
} // end of class GuessingGame

Output:

Let's play a game.  I'll pick a number between 
1 and 100, and you try to guess it. 

What is your first guess? 25 
That's too high.  Try again: 12 
That's too low.  Try again: 20 
That's too low.  Try again: 22 
That's too low.  Try again: 24 
You got it in 5 guesses!  My number was 24

Thanks for playing.  Goodbye.

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Welcome to My Blog

Translate

Popular Post

Total Pageviews

Blog Archive

- Copyright © Learning Java Program - Powered by Blogger -