编程使用for循环实现猜数字游戏(数字100以内),并统计猜了几次 提示: 1.生成100以内的随机数 Random ra = new Random(); int temp = ra.nextInt(100) + 1; 2.输入数字时,判断比随机数大或者小,当猜对时退出循环 3.最后输出这个随机数和猜的次数
时间: 2023-04-01 12:02:51 浏览: 120
可以使用以下代码实现猜数字游戏,并统计猜的次数:
import java.util.Scanner;
import java.util.Random;
public class GuessNumber {
public static void main(String[] args) {
Random ra = new Random();
int temp = ra.nextInt(100) + 1;
int count = ;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入一个数字:");
int guess = sc.nextInt();
count++;
if (guess == temp) {
System.out.println("恭喜你猜对了!");
break;
} else if (guess > temp) {
System.out.println("猜大了,请重新输入!");
} else {
System.out.println("猜小了,请重新输入!");
}
}
System.out.println("随机数是:" + temp);
System.out.println("你猜了" + count + "次。");
}
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)