用Java编写一个随机生成1-100的整数,让玩家猜数字,一共十次机会
时间: 2024-10-10 14:12:43 浏览: 44
在Java中,你可以创建一个简单的控制台游戏来实现这个功能。这里是一个基本的示例:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
private static final int MAX_NUMBER = 100;
private static final int NUM_GUESSES = 10;
private Random random;
private int secretNumber;
public static void main(String[] args) {
new GuessNumberGame().play();
}
public GuessNumberGame() {
random = new Random();
secretNumber = random.nextInt(MAX_NUMBER + 1);
}
public void play() {
Scanner scanner = new Scanner(System.in);
for (int guessCount = 1; guessCount <= NUM_GUESSES; guessCount++) {
System.out.println("第 " + guessCount + " 次猜测,请输入1到100之间的整数:");
int playerGuess = scanner.nextInt();
if (playerGuess == secretNumber) {
System.out.println("恭喜,你猜对了!你用了 " + guessCount + " 次机会。");
break;
} else if (playerGuess < secretNumber) {
System.out.println("太小了,请再试一次!");
} else {
System.out.println("太大了,请再试一次!");
}
}
if (guessCount == NUM_GUESSES + 1) {
System.out.println("很遗憾,你没猜对。正确的数字是 " + secretNumber + ".");
}
scanner.close();
}
}
```
在这个程序中,我们首先生成一个1到100的随机数作为秘密数字,然后让玩家有10次机会猜测。如果玩家猜对了,游戏结束;如果没有猜对,在规定次数内会给出提示。
阅读全文