Java for students logo
Explore the English language on a new scale using AI-powered English language navigator.

Number guessing game code snippet

Abstract

Java program playing number guessing game. Rules are:

  • Computer proposes a secret number.
  • Player tries to guess a number. Computer tells, if guess is right or smaller/greater than the secret number.
  • Number of attempts is unlimited.

Source code

NumberGuessingGame.java

import java.util.Scanner;

 

public class NumberGuessingGame {

      public static void main(String[] args) {

            int secretNumber;

            secretNumber = (int) (Math.random() * 999 + 1);

            Scanner keyboard = new Scanner(System.in);

            int guess;

            do {

                  System.out.print("Enter a guess (1-1000): ");

                  guess = keyboard.nextInt();

                  if (guess == secretNumber)

                        System.out.println("Your guess is correct. Congratulations!");

                  else if (guess < secretNumber)

                        System.out

                                   .println("Your guess is smaller than the secret number.");

                  else if (guess > secretNumber)

                        System.out

                                   .println("Your guess is greater than the secret number.");

            } while (guess != secretNumber);

      }

}

Download NumberGuessingGame.java

Sample run

Enter a guess (1-1000): 500

Your guess is greater than the secret number.

Enter a guess (1-1000): 250

Your guess is greater than the secret number.

Enter a guess (1-1000): 125

Your guess is greater than the secret number.

Enter a guess (1-1000): 62

Your guess is greater than the secret number.

Enter a guess (1-1000): 31

Your guess is smaller than the secret number.

Enter a guess (1-1000): 50

Your guess is greater than the secret number.

Enter a guess (1-1000): 40

Your guess is correct. Congratulations!

 

Extra

Check for practice lesson, explaining development of number guessing game step by step: Practice. Developing "number guessing game" step by step.