DEV Community

Cover image for Simple Number Guessing Game in Java
Foolish Developer
Foolish Developer

Posted on • Updated on

Simple Number Guessing Game in Java

In the world of programming, games provide a fascinating platform for honing your skills and creating engaging user experiences.

One such game that offers a perfect blend of fun and learning is the Number Guessing Game in Java.

In this article, we'll take you through the process of building a Number Guessing Game in Java, a versatile and widely-used programming language.

Number Guessing Game in Java

In this Number Guessing Game in Java, the computer randomly selects a number, and the player has to guess it.

The player keeps guessing until they guess the correct number. The program will provide feedback on whether the guess is too high or too low. Here's the code:

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

public class NumberGuessingGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        int lowerBound = 1; // Set the lower bound of the number range
        int upperBound = 100; // Set the upper bound of the number range
        int secretNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
        int numberOfTries = 0;
        boolean hasGuessedCorrectly = false;

        System.out.println("Welcome to the Number Guessing Game!");
        System.out.println("I've selected a random number between " + lowerBound + " and " + upperBound + ". Try to guess it.");

        while (!hasGuessedCorrectly) {
            System.out.print("Enter your guess: ");
            int userGuess = scanner.nextInt();
            numberOfTries++;

            if (userGuess < lowerBound || userGuess > upperBound) {
                System.out.println("Please guess a number between " + lowerBound + " and " + upperBound + ".");
            } else if (userGuess < secretNumber) {
                System.out.println("Too low. Try again.");
            } else if (userGuess > secretNumber) {
                System.out.println("Too high. Try again.");
            } else {
                hasGuessedCorrectly = true;
                System.out.println("Congratulations! You've guessed the number " + secretNumber + " in " + numberOfTries + " tries.");
            }
        }

        scanner.close();
    }
}

Enter fullscreen mode Exit fullscreen mode

Step by Step Explanation

Here's an explanation of the code for the number guessing game in Java:

1. Import Statements:
These statements import necessary classes for handling user input (Scanner) and generating random numbers (Random).

import java.util.Scanner;
import java.util.Random;
Enter fullscreen mode Exit fullscreen mode

2. Variable Initialization:

These variables set the lower and upper bounds for the range of numbers that the user can guess. In this example, the range is from 1 to 100.

int lowerBound = 1;
int upperBound = 100;
Enter fullscreen mode Exit fullscreen mode

3. Generating the Secret Number:

This line generates a random number within the specified range using the Random class. It ensures that the secret number is within the specified bounds.

int secretNumber = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
Enter fullscreen mode Exit fullscreen mode

4. Game Variables:

numberOfTries keeps track of how many attempts the player has made, and hasGuessedCorrectly is a boolean variable to determine if the player has guessed the correct number.

int numberOfTries = 0;
boolean hasGuessedCorrectly = false;

Enter fullscreen mode Exit fullscreen mode

5. Welcome Message:

These lines provide a welcoming message and inform the player about the range of numbers to guess from.

System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I've selected a random number between " + lowerBound + " and " + upperBound + ". Try to guess it.");

Enter fullscreen mode Exit fullscreen mode

6. Game Loop:

This while loop runs as long as the player has not guessed the correct number.

while (!hasGuessedCorrectly) {
Enter fullscreen mode Exit fullscreen mode

7. User Input and Guessing Logic:

It reads the user's input as their guess and increments the numberOfTries counter.

int userGuess = scanner.nextInt();
numberOfTries++;

Enter fullscreen mode Exit fullscreen mode

8. Checking User Input:

if (userGuess < lowerBound || userGuess > upperBound) {
    System.out.println("Please guess a number between " + lowerBound + " and " + upperBound + ".");
} else if (userGuess < secretNumber) {
    System.out.println("Too low. Try again.");
} else if (userGuess > secretNumber) {
    System.out.println("Too high. Try again.");
} else {
    hasGuessedCorrectly = true;
    System.out.println("Congratulations! You've guessed the number " + secretNumber + " in " + numberOfTries + " tries.");
}

Enter fullscreen mode Exit fullscreen mode
  • If the user's guess is outside the specified range, it prompts the user to guess within the range.
  • If the guess is lower than the secret number, it informs the user that their guess is too low.
  • If the guess is higher than the secret number, it informs the user that their guess is too high.
  • If the guess matches the secret number, it sets hasGuessedCorrectly to true, and the game loop ends. It also displays a congratulatory message with the correct number and the number of tries.

9. Closing the Scanner:

This line closes the Scanner object when the game is over.

scanner.close();
Enter fullscreen mode Exit fullscreen mode

Overall, this code creates a simple number guessing game where the player needs to guess a random number within a specified range.

It provides feedback on the player's guesses and counts the number of attempts it took to guess the correct number.

Related Post:

  1. Simple Footer HTML CSS
  2. Stopwatch using JavaScript
  3. CSS Floating Action Button
  4. Javascript Age Calculator
  5. Pre Schools in Koramangala
  6. Automatic Image Slider in Html CSS

Creating a Number Guessing Game in Java is not only a fun and educational project but also a fantastic way to enhance your programming skills.

Top comments (0)