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();
}
}