java猜字游戏代码
时间: 2024-01-29 17:09:37 浏览: 80
以下是一个简单的Java猜数字游戏的代码示例:
```java
import java.util.Random;import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random random = new Random();
int targetNumber = random.nextInt(100) + 1;
int count = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入一个1-100之间的整数:");
int guessNumber = scanner.nextInt();
count++;
if (guessNumber > targetNumber) {
System.out.println("猜的数字大了!");
} else if (guessNumber < targetNumber) {
System.out.println("猜的数字小了!");
} else {
System.out.println("恭喜你猜中了!");
break;
}
if (count >= 7) {
System.out.println("机会用完了,游戏结束!");
break;
}
}
scanner.close();
}
}
```
阅读全文