我的Tic Tac Toe程序有这个小问题。我有一个嵌套的计数器,用X片检查垂直和水平的胜利(我还没有为O做过)。出于某种原因,它永远不会结束,允许我放置越来越多的碎片。
对于某些上下文,这里有一些代码片段。
public static void game (String winner, Board pointer)
{
boolean win = false;
int turnCount = 1;
winner = "Tie";
while (win == false || turnCount < 9)
{
int row = Integer.parseInt(JOptionPane.showInputDialog(pointer.getName1() + ", it is your turn. " + "\n" + "What row would you like your 'x' to be in?"));
int col = Integer.parseInt(JOptionPane.showInputDialog("What column would you like it to be in?"));
pointer.play[row] [col] = pointer.x;
SpotCheck1(winner, pointer, row, col);
System.out.println(BoardStat(pointer));
winCheck(win, pointer, winner);
int row2 = Integer.parseInt(JOptionPane.showInputDialog(pointer.getName2() + ", it is your turn. " + "\n" + "What row would you like your 'o' to be in?"));
int col2 = Integer.parseInt(JOptionPane.showInputDialog("What column would you like it to be in?"));
SpotCheck2(winner, pointer, row2, col2);
pointer.play[row2] [col2] = pointer.o;
System.out.println(BoardStat(pointer));
winCheck(win, pointer, winner);
turnCount++;
}
//return winner;
}
public static void winCheck (boolean win, Board pointer, String winner)
{
for (int counter = 1; counter <= 3; counter++)
{
if ( pointer.play [counter] [1].compareTo(pointer.x) > 0 && pointer.play [counter] [2].compareTo(pointer.x) > 0 && pointer.play [counter] [3].compareTo(pointer.x) > 0)
{
win = true;
winner = pointer.getName1();
win(winner, pointer);
}
else if (pointer.play [1] [counter].compareTo(pointer.x) > 0 && pointer.play [2] [counter].compareTo(pointer.x) > 0 && pointer.play [3] [counter].compareTo(pointer.x) > 0)
{
win = true;
winner = pointer.getName1();
win(winner, pointer);
}
}
//return win;
}
SpotChecks 1和2是检查玩家是否已经放置一块的方法。我认为问题在于WinCheck方法。如果有人可以帮助我,那就太棒了!第一篇文章,如果我做错了,请道歉。
答案 0 :(得分:1)
您正在修改方法win
中的参数winCheck
,并且您希望这更改了方法win
中的局部变量game
。但情况并非如此 - Java按值传递方法参数,因此win
中的winCheck
是副本,任何更改都不会反映出来。您可以将方法winCheck
的返回类型设为boolean
。
public static boolean winCheck (boolean win, Board pointer, String winner)
{
// Other code is unchanged
return win;
}
在您的game
方法中,您将方法winCheck
的任何调用更改为:
win = winCheck(...);