gpt4 book ai didi

java - 通过使用二维数组创建井字棋盘

转载 作者:行者123 更新时间:2023-12-01 20:10:48 25 4
gpt4 key购买 nike

在这段代码中,我尝试创建一个二维数组来表示 tic tac toe 板(带有用户输入),但无论我在“TicTacLine”中输入什么,程序总是会显示“你从来没有玩过 Tic Tac”吗?之前?如果你没有,也没关系,但仅供引用,它会与 x 和 o 一起播放。”,这是我在 uno、dos 和 tres 中的字符既不是 x 也不是 o 时写的消息。

public class TicTacToe {

public static void main(String[] args) {
int TicTac[][]= new int[3][3];

System.out.println("Enter the Tic Tac Toe board you want to see, one line at a time.");
Scanner scanner = new Scanner(System.in);
String TicTacLine = scanner.nextLine();
int loop = 0;

if (TicTacLine.length()<3 | TicTacLine.length()>3) { // I try to define the array by a series of inputs that go in the while loop.
System.out.println("Tic-tac-toe plays in a 3×3 grid. This means if you want to input a line, you would want to input 3 characters, no more, no less.");
} else {
while (loop != 3) { // we count the loops so that there's only 3 different lines
char uno = TicTacLine.charAt(0);
char dos = TicTacLine.charAt(1);
char tres = TicTacLine.charAt(2);
if (uno != 'x' | uno != 'o' | dos != 'x' | dos != 'o' | tres != 'x' | tres != 'o') {
System.out.println("Have you never played Tic Tac Toe before ? It's okay if you haven't, but just FYI, it plays with x's and o's.");
break;
} else {
if (loop == 0) {
TicTac[0][0] = uno;
TicTac[0][1] = dos;
TicTac[0][2] = tres;
loop = ++loop;
TicTacLine = scanner.nextLine();
} if (loop == 1) {
TicTac[1][0] = uno;
TicTac[1][1] = dos;
TicTac[1][2] = tres;
loop = ++loop;
TicTacLine = scanner.nextLine();
} if (loop == 2) {
TicTac[2][0] = uno;
TicTac[2][1] = dos;
TicTac[2][2] = tres;
loop = ++loop;
TicTacLine = scanner.nextLine();
}
}
}
}
if (loop == 3) {
for(int[] row : TicTac) {
PrintingRow(row);
}
}
}
}

最佳答案

IF 语句中的 boolean 表达式将始终为 true:

if (uno != 'x' | uno != 'o' | dos != 'x' | dos != 'o' | tres != 'x' | tres != 'o')
为什么?因为您将所有六个子表达式的结果进行或运算。由于情况是至少其中三个始终为真,并且可能所有六个都为真,因此整个表达式将 始终为真。

查看按位或运算在一起的前两个 boolean 表达式。这始终返回 true,因为 uno != 'x' 为 true,或 uno != 'o' 为 true,或两者兼而有之,因此表达式将始终为 true,所以你总是会执行

System.out.println("Have you never played Tic Tac Toe before ? It's okay if you haven't, but just FYI, it plays with x's and o's.");
break;

您需要使用逻辑 OR 和 AND 重写此代码,如下所示:

if ((uno != 'x' && uno != 'o') || (dos != 'x' && dos != 'o') || (tres != 'x' && tres != 'o')) {

这表示,如果 uno 不是“x”并且 uno 不是“o”,则评估为 trueor 评估为 true 如果 dos 不是“x”并且 dos 不是“o”,如果 tres 不是“x”并且 tres 不是“o”,or 计算结果为 true

有关 Java 运算符的更多信息,Oracle 在此处提供了很好的文档:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

关于java - 通过使用二维数组创建井字棋盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46746051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com