编写一个java程序实现的小游戏
时间: 2024-05-24 22:13:23 浏览: 13
以下是一个简单的Java程序,实现了猜数字的小游戏:
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
System.out.println("欢迎来到猜数字游戏!");
System.out.println("我已经想好了一个1到100之间的整数。");
System.out.println("请你猜一下这个数是多少。");
Random random = new Random();
int number = random.nextInt(100) + 1;
int guess = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (guess != number) {
System.out.print("请输入你猜测的数字:");
guess = input.nextInt();
count++;
if (guess < number) {
System.out.println("你猜测的数字太小了!");
} else if (guess > number) {
System.out.println("你猜测的数字太大了!");
} else {
System.out.println("恭喜你,猜对了!");
System.out.println("你总共猜了" + count + "次。");
}
}
}
}
运行程序后,会随机生成一个1到100之间的整数,然后让玩家输入猜测的数字,程序会根据玩家输入的数字给出提示,直到猜对为止。程序还会记录玩家猜测的次数,并在猜对后输出总共猜了多少次。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)