Java编程实现猜数字游戏。在[1,100]之间猜数字。规则如下:1、如果猜小了,会提示猜小了;2、如果猜大了,提示猜大了;3、如果猜中了,提示猜中了,并输出您一共猜的次数;4、每次游戏选手最多能猜10次;
时间: 2024-06-12 22:08:26 浏览: 11
在Java编程中,可以通过以下代码实现猜数字游戏:
```java
import java.util.Scanner;
import java.util.Random;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int target = random.nextInt(100) + 1; // 生成1到100之间的随机整数
int attempts = 0; // 记录猜测次数
while (attempts < 10) {
System.out.print("请输入你猜的数字:");
int guess = input.nextInt();
attempts++;
if (guess < target) {
System.out.println("猜小了!");
} else if (guess > target) {
System.out.println("猜大了!");
} else {
System.out.println("猜中了!");
System.out.println("你一共猜了" + attempts + "次。");
break;
}
}
if (attempts == 10) {
System.out.println("很遗憾,你没有猜中。正确答案是" + target + "。");
}
}
}
```
这段代码会生成一个1到100之间的随机整数作为目标数字,然后通过用户输入进行猜测,如果猜小了,会提示猜小了;如果猜大了,会提示猜大了;如果猜中了,会输出猜的次数,并结束游戏;如果猜测次数达到10次仍未猜中,会提示很遗憾并显示正确答案。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)