我正在开展Tic-Tac-Toe项目,在该项目中我导入了X' s和O&#39>的9个字符串:
XOOXXOOXX
然后我必须拆开它,将其加载到3x3矩阵中,然后测试并看看谁赢了比赛。我编写了加载文件的代码并像这样运行游戏:
public static void main( String args[] ) throws IOException
{
Scanner importer = new Scanner(new File("testdata.dat"));
int count = importer.nextInt();
System.out.println(count + " games to test.");
for(int i = 0; i < count; i++) {
String game = importer.next();
TicTacToe gamecalc = new TicTacToe();
System.out.println(gamecalc.getWinner(game));
}
}
但是,当我尝试加载已经建立的3x3矩阵时:
String gamedata = game; //gamedata is passed in, reassigned to game
for(int line = 0; line < 2; line++) {
for(int column = 0; column < 2; column++) {
gamemat[line][column] = game.charAt(line * column);
}
}
,数据集为:
abcdefghi
jklmnopqr
stuvwxyz1
234567890
ABCDEFGHI
当使用Arrays.toString打印时,结果最终成为:
[a, a, ][a, b, ][ , , ] //each line is one 3x3 matrix
[j, j, ][j, k, ][ , , ]
[s, s, ][s, t, ][ , , ]
[2, 2, ][2, 3, ][ , , ]
[A, A, ][A, B, ][ , , ]
如何重新编写算法以使矩阵正确加载?谢谢!
答案 0 :(得分:0)
我认为这条线错了......
gamemat[line][column] = game.charAt(line * column);
应该是......
gamemat[line][column] = game.charAt(line * 3 + column);
此外,您可能希望循环计数最多3 ...
for(line = 0; line < 3; line++)...