【发布时间】:2018-03-26 13:01:08
【问题描述】:
在这段代码中,我尝试创建一个代表井字游戏的二维数组(使用用户输入),但无论我在“TicTacLine”中输入什么内容,程序总是会弹出“你从未玩过井字游戏” Toe before ?如果你没有也可以,但仅供参考,它与 x's 和 o's 一起使用。 >
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);
}
}
}
}
【问题讨论】:
-
确保使用 .equals 而不是 == 来比较字符串。此外,您正在使用 |而不是 ||为“或”。此外,在“TicTacLine.length()3”行中,您可以改用“TicTacLine.length() != 3”。此外,只是你应该使用的 java 中的一个约定:你在 java 中命名了一个变量“TicTacLine”,我们使用 lowerCamelCase 所以它应该重命名为:“ticTacLine”你的类名,“TicTacToe”很好,类名使用 PascalCase .编辑:您正在以正确的方式比较字符。我以为那些是字符串。
-
想一想:
uno的什么值会使uno != 'x' | uno != 'o'成为false?它必须是&&。 -
我确实更改了我的变量名称和 ticTacLine.length() != 3 但它不会使错误消息消失。
标签: java arrays multidimensional-array tic-tac-toe