j ava猜数字小游戏
时间: 2023-10-22 19:57:17 浏览: 325
java猜数字小游戏
Sure! I can help you with a simple number guessing game in Java. Here's an example code:
```java
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Random random = new Random();
int secretNumber = random.nextInt(100) + 1;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
int guess;
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I'm thinking of a number between 1 and 100.");
do {
System.out.print("Take a guess: ");
guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("Too low! Try again.");
} else if (guess > secretNumber) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You guessed the number in " + attempts + " attempts.");
}
} while (guess != secretNumber);
scanner.close();
}
}
```
In this game, the program generates a random number between 1 and 100, and the user has to guess the correct number. The program provides feedback on whether the guess is too low or too high. The game continues until the user guesses the correct number.
阅读全文