java数组猜数字游戏
时间: 2023-12-05 09:39:41 浏览: 81
Java实现的猜数字游戏示例
以下是Java数组猜数字游戏的示例代码:
```java
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
int[] answer = {1, 2, 3, 4}; // 答案数组
int[] guess = new int[4]; // 玩家猜测的数组
Scanner scanner = new Scanner(System.in);
// 循环猜测,直到猜对为止
while (true) {
// 提示玩家输入猜测的数字
System.out.println("请输入4个数字,用空格分隔:");
for (int i = 0; i < 4; i++) {
guess[i] = scanner.nextInt();
}
// 检查猜测的数字是否正确
int a = 0, b = 0;
for (int i = 0; i < 4; i++) {
if (guess[i] == answer[i]) {
a++;
} else {
for (int j = 0; j < 4; j++) {
if (guess[i] == answer[j]) {
b++;
break;
}
}
}
}
// 输出猜测结果
System.out.println(a + "A" + b + "B");
// 如果猜对了,退出循环
if (a == 4) {
System.out.println("恭喜你猜对了!");
break;
}
}
}
}
```
阅读全文