The number guessing game is a classic beginner project that introduces core programming concepts in a fun and engaging way. In this article, we'll walk through creating a number-guessing game in Java, explaining the code, and showcasing example output1. The game involves the computer generating a random number and the player attempting to guess that number within a certain range.

Number guessing Game Logic

Here's the basic outline of how the game works:

Code example

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

public class NumberGuessingGame {

    public static void main(String[] args) {
        Random rand = new Random();
        int numberToGuess = rand.nextInt(100) + 1; // Generates random number between 1 and 100
        Scanner scanner = new Scanner(System.in);
        int guess;

        System.out.println("Welcome to the number guessing game!");
        System.out.println("Guess a number between 1 and 100:");

        while (true) {
            guess = scanner.nextInt();

            if (guess == numberToGuess) {
                System.out.println("Congratulations, you guessed the number!");
                break;
            } else if (guess < numberToGuess) {
                System.out.println("Your guess is too low. Try again:");
            } else {
                System.out.println("Your guess is too high. Try again:");
            }
        }

        scanner.close();
    }
}

Explanation

Output

Number guessing game Java

Number guessing game Java

Enhancements

Here are some ways to enhance the game:

Conclusion

The number guessing game is a simple yet effective project for learning basic programming concepts in Java1. This article provides a clear and concise guide to building the game, along with suggestions for enhancements to make it more challenging and engaging.