This question already has answers here:
Is Java “pass-by-reference” or “pass-by-value”?
(87个答案)
4年前关闭。
我的Tic Tac Toe程序有这个小问题。我有一个嵌套的计数器,用于检查X片的垂直和水平胜利(我还没有为O做过)。由于某种原因,它永无止境,让我可以放置越来越多的作品。
对于某些上下文,这是一些代码片段。
SpotChecks 1和2是检查玩家是否已放置棋子的方法。我认为问题出在WinCheck方法中。如果有人可以帮助我,那就太好了!第一篇文章,如果我做错了事,我深表歉意。
然后在您的
(87个答案)
4年前关闭。
我的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方法中。如果有人可以帮助我,那就太好了!第一篇文章,如果我做错了事,我深表歉意。
最佳答案
您正在修改方法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(...);
关于java - 井字游戏程序无法识别获胜者,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37461238/
10-13 03:30