High Low Guessing Game

Java 17.5.2011 5 Comments

The assignment here is to write a simple game where the user tries to guess a randomly selected number. After each guess the application tells the user if the guess is too high or too low. This is repeated until the user finally guesses the number.

First thing we need is to generate a random number. To achieve this Java provides the java.util.Random class with its nextInt() method providing exactly what we need (see line 31).

Then we want to repeatedly prompt the user to guess the number until they get it right. For this we can use a while loop (see line 36). For each loop iteration we prompt the user to make a guess, and read their input. That input is then compared with the random number we generated earlier.

And that’s about, look over the code and ask if anything isn’t clear. Or better still become a member and one of our Java mentors can guide you.

package com.learnjava.console;

import java.util.Random;
import java.util.Scanner;

/**
 * Write a guessing game where the user tries to 
 * guess the number randomly picked by the computer.
 * For each guess tell the user if the 
 * guess is too high, low or correct.
 * 
 * @author https://learn-java-by-example.com
 *
 */

public class HighLowGuessingGame {

	public static void main(String[] args) {

		// Create a random number generator
		
		Random random = new Random();

		// Use Scanner for getting input from user
		
		Scanner scanner = new Scanner(System.in);
		
		// Use the random generator to 
		// pick a number between 0 and 99 (inclusive)
		
		int number = random.nextInt(100);
		int guess = -1;
		
		// Loop until the user has guessed the number
		
		while (guess!=number) {
			
			// Prompt the user for their next guess
			
			System.out.print("Enter your guess: ");
			
			// Read the users guess
			
			guess = scanner.nextInt();
			
			// Check if the guess is high, low or correct
			
			if (guess<number) {
				
				// Guess is too low
				
				System.out.println("Too low, please try again");
				
			} else if (guess>number) {

				// Guess is too high

				System.out.println("Too high, please try again");
				
			} else {
				
				// Guess is correct !!
				
				System.out.println("Correct, the number was " + number);
			}
		}
	}

}

5 Responses to “High Low Guessing Game”

  1. java.lang.outofmemoryerror in java

    great example , I always believe that game programming can improve your programming drastically.

  2. Dylan P.

    hi this is great code thanks fam.

  3. zahra

    how can we keep track of the number of times the user guess?

  4. Betsey

    Well I guess I don’t have to spend the weekend fiugirng this one out!

Leave a Reply

s2Member®