java猜数字1到100游戏
时间: 2023-11-29 16:46:19 浏览: 73
以下是Java实现1到100猜数字游戏的代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1;
int numberOfTries = 0;
boolean win = false;
System.out.println("欢迎来到猜数字游戏!");
System.out.println("游戏规则:猜一个1到100之间的数字,看看你能否猜中!");
while (!win) {
System.out.print("请输入你猜测的数字:");
String input = scanner.nextLine();
// 验证输入是否为数字
if (!input.matches("\\d+")) {
System.out.println("请输入数字!");
continue;
}
int guess = Integer.parseInt(input);
numberOfTries++;
if (guess < numberToGuess) {
System.out.println("你猜的数字太小了,请再试一次!");
} else if (guess > numberToGuess) {
System.out.println("你猜的数字太大了,请再试一次!");
} else {
win = true;
System.out.println("恭喜你,猜对了!");
System.out.println("你猜了" + numberOfTries + "次。");
if (numberOfTries <= 5) {
System.out.println("你真是个天才!");
} else if (numberOfTries <= 10) {
System.out.println("不错哦,继续加油!");
} else {
System.out.println("要不再试一次?");
}
System.out.print("是否继续游戏?[Y/N]");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("N")) {
System.out.println("游戏结束,再见!");
break;
} else {
numberToGuess = random.nextInt(100) + 1;
numberOfTries = 0;
win = false;
}
}
}
}
}
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)