我试图创建一个Tic Tac Toe游戏,用户实际上输入了主板并且程序告诉他哪一方获胜,或者是否有抽奖,而不是在棋盘上没有任何内容。 。使用二维数组,我想让用户输入是一个单独的行,然后取出字符并将它们放入数组中。该程序将根据通过while循环的次数确定输入字符的位置。但是,我遇到了多个问题:程序不只需要3个输入,需要更多,并且当输入的长度不是3时,应该提出错误信息有时显示。最后,当阵列显示时,它会显示数字而不是x和o。
import java.util.*;
public class TicTacToe {
public static void PrintingRow(int[] row) { // we define how we want the board to be displayed (i.e. no brackets and no commas.)
for (int i : row) {
System.out.print(i); }
System.out.println();
}
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);
int loop = 0;
while (loop != 3) { // we count the loops so that there's only 3 different lines
String ticTacLine = scanner.nextLine();
if (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 {
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();
} else if (loop == 1) {
TicTac[1][0] = uno;
TicTac[1][1] = dos;
TicTac[1][2] = tres;
loop = ++loop;
ticTacLine = scanner.nextLine();
} else 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);
} }
// Here we want to check what character won (x's or o's)
}
}