用Java编写猜数字游戏
时间: 2024-10-14 10:15:35 浏览: 50
在Java中,我们可以编写一个简单的猜数字游戏,通常游戏规则会有一个随机数生成器,然后让用户猜测这个数,直到猜对为止。以下是基本的游戏实现步骤:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 100;
private int secretNumber;
private Scanner scanner;
public GuessNumberGame() {
generateRandomNumber();
}
private void generateRandomNumber() {
Random random = new Random();
secretNumber = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
}
public boolean isCorrectGuess(int guess) {
if (guess == secretNumber) {
System.out.println("恭喜你,猜对了!");
return true;
} else if (guess < secretNumber) {
System.out.println("猜小了,再试一次。");
} else {
System.out.println("猜大了,再试一次。");
}
return false;
}
public void startGame() {
scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入你猜的数字:");
int userGuess = scanner.nextInt();
if (isCorrectGuess(userGuess)) {
break;
}
}
}
public static void main(String[] args) {
GuessNumberGame game = new GuessNumberGame();
game.startGame();
}
}
阅读全文