To create a "guess the number" game in Java, you can use a loop to repeatedly prompt the user for a guess and check if the guess is correct.
Here's an example of how you can do this:
import java.util.Scanner; public class GuessTheNumber { public static void main(String[] args) { int secretNumber = (int) (Math.random() * 10) + 1; // random number between 1 and 10 Scanner scanner = new Scanner(System.in); int guess; do { System.out.print("Enter your guess (1-10): "); guess = scanner.nextInt(); if (guess < secretNumber) { System.out.println("Your guess is too low"); } else if (guess > secretNumber) { System.out.println("Your guess is too high"); } } while (guess != secretNumber); System.out.println("You guessed the secret number: " + secretNumber); } }
This code generates a random secret number between 1 and 10 and prompts the user to enter a guess. If the guess is incorrect, it tells the user whether the guess was too low or too high. The loop continues until the user guesses the correct number.
You can customize the game by changing the range of the secret number, adding a limit on the number of guesses, or adding additional features such as difficulty levels or a scoring system.