0% found this document useful (0 votes)
20 views

Number Guessing Game Using Java

The document describes a number guessing game program written in Java that generates a random number between 1 and 100 and allows the user to guess the number within a set number of attempts, providing feedback if each guess is too high or too low until the user guesses correctly or reaches the maximum number of attempts.

Uploaded by

poopathirajap03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Number Guessing Game Using Java

The document describes a number guessing game program written in Java that generates a random number between 1 and 100 and allows the user to guess the number within a set number of attempts, providing feedback if each guess is too high or too low until the user guesses correctly or reaches the maximum number of attempts.

Uploaded by

poopathirajap03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

NUMBER GUESSING GAME USING

JAVA

PROGRAM:
import java.util.Random;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// Create a Random object to generate a random number
Random random = new Random();
int randomNumber = random.nextInt(100) + 1; // Generates a random
number between 1 and 100

// Create a Scanner object to get user input


Scanner scanner = new Scanner(System.in);

// Set a predefined limit for attempts


int maxAttempts = randomNumber;
int attempts = 0;

System.out.println("Welcome to the Number Guessing Game!");


System.out.println("Try to guess the number between 1 and 100.");

// Start the game loop


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

// Compare the user's guess with the generated number


if (userGuess == randomNumber) {
System.out.println("Congratulations! You guessed the correct number
in " + attempts + " attempts.");
break; // Exit the loop if the guess is correct
} else if (userGuess < randomNumber) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}

// Check if the maximum number of attempts is reached


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

// Close the scanner to prevent resource leak


scanner.close();
}
}

You might also like