Java
Java

 

Introduction

In this game, the computer will randomly select a number, and the player will have to guess it. The game will provide feedback if the guess is too low or too high, and the player will continue guessing until they get the correct answer. This game is a great introduction to random number generation, user input handling, and basic loops in Java programming.

Objective

The main objective of this project is to create an interactive console-based game where the computer picks a random number between a specified range, and the player attempts to guess it. The game will:

  • Generate a random number within a predefined range (e.g., 1 to 100).
  • Prompt the user to enter a guess.
  • Provide feedback whether the guess is too high, too low, or correct.
  • Continue prompting until the correct number is guessed.

Java Code


public class NumberGuessingGame {
    public static void main(String[] args) {
        // Create a Random object to generate random numbers
        java.util.Random random = new java.util.Random();
        
        // Set the range for the random number (1 to 100)
        int lowerBound = 1;
        int upperBound = 100;
        
        // Generate the random number
        int numberToGuess = random.nextInt(upperBound - lowerBound + 1) + lowerBound;
        
        // Initialize the Scanner to get user input
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        
        int userGuess = 0;
        int attempts = 0;
        
        System.out.println("Welcome to the Number Guessing Game!");
        System.out.println("I have selected a number between " + lowerBound + " and " + upperBound + ". Try to guess it!");
        
        // Game loop: Keep asking for guesses until the correct number is guessed
        while (userGuess != numberToGuess) {
            System.out.print("Enter your guess: ");
            userGuess = scanner.nextInt();
            attempts++;
            
            if (userGuess < numberToGuess) { System.out.println("Too low! Try again."); } else if (userGuess > numberToGuess) {
                System.out.println("Too high! Try again.");
            } else {
                System.out.println("Congratulations! You guessed the correct number!");
                System.out.println("It took you " + attempts + " attempts.");
            }
        }
        
        // Close the scanner object
        scanner.close();
    }
}
        

Explanation of the Program Structure

The program follows a simple structure:

  1. Random Number Generation: The program starts by generating a random number between a specified range (1 and 100 in this case). This is done using Java’s Random class.
  2. User Input: The program uses the Scanner class to get input from the user. The user’s guess is stored in the userGuess variable.
  3. Game Loop: A while loop is used to repeatedly ask the user for guesses until the correct number is guessed. Inside the loop, the program provides feedback if the guess is too high, too low, or correct.
  4. Attempts Tracking: The number of attempts the user makes is tracked and displayed once the game ends, providing an additional layer of feedback to the player.

How to Run the Program

  1. Install Java: Make sure you have Java installed on your computer. You can download it from the official Oracle website or use OpenJDK.
  2. Create a New File: Open a text editor and create a new file named NumberGuessingGame.java.
  3. Copy and Paste the Code: Copy the Java code provided above and paste it into your NumberGuessingGame.java file.
  4. Compile the Program: Open a terminal or command prompt and navigate to the directory where you saved the NumberGuessingGame.java file. Then, run the following command to compile the program:
    javac NumberGuessingGame.java
    
  5. Run the Program: After compiling, run the program with the following command:
    java NumberGuessingGame
    
  6. Play the Game: The program will prompt you to guess the number. Enter your guesses and receive feedback until you guess the correct number!

Conclusion

This simple number guessing game demonstrates how to use random number generation, user input, and loops in Java. It’s a great beginner project for learning the basics of programming and Java syntax. You can extend this game by adding additional features like a timer, difficulty levels, or keeping track of high scores.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)