java猜一到十随机数
时间: 2023-09-28 15:07:59 浏览: 103
下面是一个可以用Java猜测1到10之间的随机数的代码示例:
```java
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int randomNumber = (int)(Math.random() * 10) + 1;
int guessNumber = 0;
int count = 0;
while (true) {
System.out.println("请输入你猜测的数字");
guessNumber = input.nextInt();
count++;
if (guessNumber > randomNumber) {
System.out.println("太大了");
} else if (guessNumber == randomNumber) {
System.out.println("猜对了");
System.out.println("一共猜测了" + count + "次");
break;
} else if (guessNumber < randomNumber) {
System.out.println("太小了");
}
}
}
}
```
这段代码使用了一个while循环来持续接受用户的猜测,直到猜对为止。每次循环中,程序会提示用户输入猜测的数字,并将用户的输入与生成的随机数进行比较。如果猜测的数字大于随机数,程序会输出"太大了";如果猜测的数字等于随机数,程序会输出"猜对了"并显示猜测次数;如果猜测的数字小于随机数,程序会输出"太小了"。
希望这个代码示例对您有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [JAVA 猜随机数](https://blog.csdn.net/s_y_b_h/article/details/121640551)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [java 猜系统获取的随机数](https://blog.csdn.net/weixin_42365170/article/details/114449462)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文