java客户端猜数字游戏代码
时间: 2024-12-15 10:24:37 浏览: 7
在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 static Random random = new Random();
private int secretNumber;
public GuessNumberGame() {
secretNumber = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
}
public void startGame() {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到猜数字游戏!我想了一个1到100之间的数,请你猜测。");
while (true) {
System.out.print("请输入你的猜测:");
int guess = scanner.nextInt();
if (guess < secretNumber) {
System.out.println("太小了,再试一次!");
} else if (guess > secretNumber) {
System.out.println("太大了,再试试!");
} else {
System.out.println("恭喜你,猜对了!秘密数字就是 " + secretNumber);
break;
}
}
scanner.close();
}
public static void main(String[] args) {
GuessNumberGame game = new GuessNumberGame();
game.startGame();
}
}
阅读全文