如何用java写猜数字小游戏
时间: 2024-10-12 21:16:50 浏览: 30
编写一个简单的Java猜数字游戏通常包含以下几个步骤:
1. 首先,你需要创建一个随机数生成器,比如使用 `Random` 类生成1到某个范围内的随机整数作为答案。
```java
import java.util.Random;
Random random = new Random();
int secretNumber = random.nextInt(100) + 1; // 例如1到100之间的随机数
```
2. 然后,你可以创建一个循环,提示用户输入猜测,并检查其是否正确。
```java
Scanner scanner = new Scanner(System.in);
int guess;
while (true) {
System.out.println("请输入你的猜测(1-100):");
guess = scanner.nextInt();
if (guess < secretNumber) {
System.out.println("太小了!");
} else if (guess > secretNumber) {
System.out.println("太大了!");
} else {
System.out.println("恭喜,你猜对了!");
break;
}
}
```
3. 游戏结束后,记得关闭 `Scanner` 对象。
```java
scanner.close();
```
完整的简单代码示例如下:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random random = new Random();
int secretNumber = random.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Guess the number between 1 and 100: ");
int guess = scanner.nextInt();
if (guess == secretNumber) {
System.out.println("Congratulations! You guessed it correctly!");
break;
} else if (guess < secretNumber) {
System.out.println("Too low!");
} else {
System.out.println("Too high!");
}
}
scanner.close();
}
}
```
阅读全文