DEV Community

Elmo Nickol
Elmo Nickol

Posted on

Mastering the Number Guessing Game in Java

Introduction:

Welcome, fellow developers, to a journey into the realm of Java programming! In this blog post, we'll explore a simple yet engaging project – the Number Guessing Game. This project is a great way to get hands-on experience with Java basics, including user input, random number generation, and control flow. So, let's dive into the source code and unravel the magic behind this game.

Setting Up the Game:

The Java source code begins with the essential imports – java.util.Scanner for user input and java.util.Random for generating random numbers. The NumberGuessing class is then declared, and instances of Scanner and Random are created.

Scanner s = new Scanner(System.in);
Random r = new Random();
Enter fullscreen mode Exit fullscreen mode

The game's configuration parameters are set, defining the lower and upper bounds of the secret number, and the secret number itself is generated within this range.

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

User Interaction:

The game welcomes the player and prompts them to guess a number within the specified range. The user's input is then captured using the Scannerobject.

System.out.println("Welcome to Number Guessing Game!");
System.out.println("Enter a number between " + lowerBound + " to " + upperBound);
Enter fullscreen mode Exit fullscreen mode

Game Loop:

The core of the game lies in the while loop, where the player has a limited number of attempts to guess the secret number. The loop iterates until the player correctly guesses the number or exhausts all attempts.

while (attempts < maxAttempts) {
    // Code for user input and feedback
}
Enter fullscreen mode Exit fullscreen mode

Inside the loop, the player is prompted to enter their guess, and the program provides feedback based on the comparison between the guess and the secret number. If the guess is too low or too high, the player is informed accordingly. If the guess is correct, a congratulatory message is displayed, and the loop breaks.

if (userGuess < secretNumber) {
    System.out.println("Too low! Try higher than " + userGuess);
} else if (userGuess > secretNumber) {
    System.out.println("Too high! Try lower than " + userGuess);
} else {
    System.out.println("Congratulations! You guessed the number " + secretNumber + " in " + attempts + " attempts.");
    break;
}
Enter fullscreen mode Exit fullscreen mode

Game Outcome:

After the loop, the program checks if the player has reached the maximum number of attempts without guessing correctly. In that case, the correct number is revealed.

if (attempts == maxAttempts) {
    System.out.println("Sorry! You've reached the maximum number of attempts. The correct number was: " + secretNumber);
}
Enter fullscreen mode Exit fullscreen mode

Closing:

Finally, the Scanner is closed to prevent resource leaks.

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

Congratulations! You've just explored the Java source code for a simple Number Guessing Game. This project serves as an excellent starting point for beginners to practice fundamental Java concepts. Feel free to modify and enhance the game, adding features like score tracking or a graphical user interface, to further polish your Java skills. Happy coding!

Here's the full source code for the Number Guessing Game in Java:

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

public class NumberGuessing {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        Random r = new Random();

        int lowerBound = 1;
        int upperBound = 100;
        int secretNumber = r.nextInt(upperBound - lowerBound + 1) + lowerBound;

        System.out.println("Welcome to Number Guessing Game!");
        System.out.println("Enter a number between " + lowerBound + " to " + upperBound);

        int userGuess;
        int attempts = 0;
        int maxAttempts = 10;

        while (attempts < maxAttempts) {
            System.out.print("Enter your guess: ");
            userGuess = s.nextInt();
            attempts++;

            if (userGuess < secretNumber) {
                System.out.println("Too low! Try higher than " + userGuess);
            } else if (userGuess > secretNumber) {
                System.out.println("Too high! Try lower than " + userGuess);
            } else {
                System.out.println("Congratulations! You guessed the number " + secretNumber + " in " + attempts + " attempts.");
                break;
            }
        }

        if (attempts == maxAttempts) {
            System.out.println("Sorry! You've reached the maximum number of attempts. The correct number was: " + secretNumber);
        }

        s.close();

    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)