November 4, 2013 Leave a comment Go to comments

Command line interface guessing game code in Java:

 

 

package guessinggame;
import java.util.Scanner;
import java.util.Random;

public class GuessingGame {

    public static void main(String[] args) {
        // Define Scanner object so we can get user input
        Scanner in = new Scanner(System.in);

        // Set a random number
        Random r = new Random();
        int number = r.nextInt(101);

        // Print welcome message
        System.out.println("Welcome to the guessing game.");
        System.out.println("I'm thinking of a number from 0 to 100...");
        
        // Get a guess from the user
        System.out.println("Enter your guess: ");
        int guess = in.nextInt();
        
        // Process guesses until they get it right
        while (guess != number){
            if(guess < number){
                System.out.println("Guess higher!");                
            } 
            else {
                System.out.println("Guess lower!");                
            }
            System.out.println("Enter your guess: ");
            guess = in.nextInt();
        }
        // print well done message
        System.out.println("Well done! You got it!");        
    }
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s