import java.util.Random; import java.util.Scanner; public class GuessingGame { public static void main(String[] args) { // Generate a random number between 1 and 100 Random random = new Random(); int secretNumber = random.nextInt(100) + 1; Scanner scanner = new Scanner(System.in); System.out.println("Welcome to the Guessing Game!"); System.out.println("Try to guess the secret number between 1 and 100."); int attempts = 0; while (true) { System.out.print("Enter your guess: "); if (!scanner.hasNextInt()) { // If the input is not an integer, skip this iteration System.out.println("Invalid input. Please enter a valid number."); scanner.next(); // Consume the invalid input continue; } int userGuess = scanner.nextInt(); attempts++; if (userGuess == secretNumber) { System.out.println("Congratulations! You guessed the correct number in " + attempts + " attempts."); break; // Exit the loop when the correct guess is made } else if (userGuess < secretNumber) { System.out.println("Try again. The secret number is greater than your guess."); } else { System.out.println("Try again. The secret number is less than your guess."); } } scanner.close(); } }