java文字游戏代码
时间: 2024-06-23 20:01:02 浏览: 169
Java文字游戏通常涉及到用户交互、逻辑判断和简单的游戏循环。以下是一个简单的猜数字游戏的代码示例,使用了随机数生成和用户输入:
```java
import java.util.Scanner;
import java.util.Random;
public class GuessNumberGame {
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 100;
private static Random random = new Random();
private int secretNumber;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
GuessNumberGame game = new GuessNumberGame();
game.startGame(scanner);
}
public void startGame(Scanner scanner) {
secretNumber = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
System.out.println("欢迎来到猜数字游戏!我想了一个1到100之间的数字,请你猜一猜是多少:");
while (true) {
int guess = scanner.nextInt();
if (guess < secretNumber) {
System.out.println("太小了,再试一次:");
} else if (guess > secretNumber) {
System.out.println("太大了,再试一次:");
} else {
System.out.println("恭喜你,猜对了!秘密数字就是 " + secretNumber);
break;
}
}
}
}
阅读全文