Untitled
unknown
plain_text
2 months ago
1.3 kB
1
Indexable
import java.util.Scanner; import java.util.Random; public class GuessTheNumberGame { public static void main(String[] args) { // Create a Scanner object for user input Scanner scanner = new Scanner(System.in); // Create a Random object to generate a random number Random random = new Random(); // Generate a random number between 1 and 100 int targetNumber = random.nextInt(100) + 1; // Initialize variables int guess = 0; int attempts = 0; // Start game System.out.println("Welcome to Guess the Number!"); System.out.println("I have chosen a number between 1 and 100."); System.out.println("Can you guess what it is?"); // Loop until the player guesses the correct number while (guess != targetNumber) { // Prompt the user for a guess System.out.print("Enter your guess: "); guess = scanner.nextInt(); // Increment attempt counter attempts++; // Provide feedback on the guess if (guess < targetNumber) { System.out.println("Too low! Try again."); } else if (guess > targetNumber) {
Editor is loading...
Leave a Comment