用java写让用户猜数
时间: 2024-10-07 19:07:18 浏览: 19
在Java中编写一个简单的猜数字游戏,可以让用户猜测一个随机生成的整数,通常可以按照以下步骤进行:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 100; // 可根据需要调整范围
private static int secretNumber;
public static void main(String[] args) {
generateSecretNumber();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("欢迎来到猜数字游戏!我想了一个1到" + MAX_NUMBER + "之间的整数,请你猜一猜是多少:");
int guess = scanner.nextInt();
if (guess < secretNumber) {
System.out.println("太小了,再试一次!");
} else if (guess > secretNumber) {
System.out.println("太大了,再试试!");
} else {
System.out.println("恭喜你,猜对了!你真棒!");
break;
}
}
scanner.close();
}
private static void generateSecretNumber() {
Random random = new Random();
secretNumber = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
}
}
阅读全文