由于某些原因,当我编写getWinner()时,它仅适用于2种情况(最后一行)。对于对角线和列,我还有其他所有东西,但是第2行(好吧,三个,但数组,所以2)只能与o一起使用。当o在0,0和1,1或0,2和1,1时,x才获胜。 (基本上,只有当o位于顶角和中心时。
import java.util.Scanner;
public class TicTacToeRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String player = "x";
TicTacToe game = new TicTacToe();
boolean done = false;
while (!done)
{
System.out.print(game.toString());
System.out.print(
"Row for " + player + " (-1 to exit): ");
int row = in.nextInt();
if (row < 0)
{
done = true;
}
else if (row > 2)
System.out.println("Invalid, please enter a number from 0 to 2");
else
{
System.out.print("Column for " + player + ": ");
int temp = in.nextInt();
if (temp>2)
System.out.println("Invalid, please enter a number from 0 to 2");
else
{
int column = temp;
game.set(row, column, player);
if (player.equals("x"))
player = "o";
else
player = "x";
}
if(game.getWinner().equals("x"))
{
System.out.println("x is the winner!");
done = true;
}
if(game.getWinner().equals("o"))
{
System.out.println("o is the winner!");
done = true;
}
}
}
}
}
public class TicTacToe
{
private String[][] board;
private static final int ROWS = 3;
private static final int COLUMNS = 3;
public TicTacToe()
{
board = new String[ROWS][COLUMNS];
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
board[i][j] = " ";
}
public void set(int i, int j, String player)
{
if (board[i][j].equals(" "))
board[i][j] = player;
//what if the spot is filled???
}
public String toString()
{
String r = "";
for (int i = 0; i < ROWS; i++)
{
r = r + "|";
for (int j = 0; j < COLUMNS; j++)
r = r + board[i][j];
r = r + "|\n";
}
return r;
}
public String getWinner() //which one isn't working? I tried a few attempts at the third col and third row, and both worked.
{
for (int i = 0; i <= 2; i++) //HORIZONTAL
{
if (board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2]))
return board[i][0];
}
for (int j = 0; j <= 2; j++) //VERTICAL
{ if (board[0][j].equals(board[1][j]) && board[1][j].equals(board[2][j]))
return board[0][j];
}
if (board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2]))
return board[0][0];
if (board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0]))
return board[1][1];
return " ";
}
} 有什么建议吗?
答案 0 :(得分:2)
如果行,列或对角线中没有空格,则它们都是" "
。但是,这仍然会满足条件,例如
board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2])
然后它将立即返回" "
而不检查其他位置。 " "
是赢家!但你也使用" "
表示没有赢家。
在检查条件表达式的其余部分之前,为您的条件添加一个额外的检查,以确保您检查的第一个位置不等于" "
:
!" ".equals(board[i][0]) &&
board[i][0].equals(board[i][1]) &&
board[i][1].equals(board[i][2])
你可以同样改变其他条件。