用java写 生成1到10任意一个数(使用Random)类实现随机值,用户输入整数猜三次猜大猜小都给提示
时间: 2024-09-20 11:09:10 浏览: 51
在Java中,你可以使用`Random`类配合循环和条件判断来实现这个猜数字游戏。首先,你需要创建一个随机数,然后让用户输入猜测,比较用户输入和随机数,给出相应的提示。以下是简单的代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
private static final int MIN = 1;
private static final int MAX = 10;
private Random random;
private int secretNumber;
public static void main(String[] args) {
GuessNumberGame game = new GuessNumberGame();
Scanner scanner = new Scanner(System.in);
while (true) {
game.generateSecretNumber();
System.out.println("欢迎来到猜数字游戏! 请输入你认为1到10之间的数字,你有三次机会猜测。");
for (int i = 1; i <= 3; i++) {
System.out.print("第" + i + "次猜测:");
int guess = scanner.nextInt();
if (guess < game.secretNumber) {
System.out.println("太小了!");
} else if (guess > game.secretNumber) {
System.out.println("太大了!");
} else {
System.out.println("恭喜你,猜对了! 你在第" + i + "次尝试就成功了。");
break;
}
}
if (i == 3) {
System.out.println("很遗憾,你没能在三次内猜对,正确的数字是:" + game.secretNumber);
}
System.out.println("是否再来一局?(y/n)");
String response = scanner.next().toLowerCase();
if (!response.equals("y")) {
break;
}
}
scanner.close();
}
private void generateSecretNumber() {
random = new Random();
secretNumber = random.nextInt(MAX - MIN + 1) + MIN;
}
}
```
阅读全文