我没有收到任何编译错误但是必须存在逻辑错误,因为我的checkWinner方法甚至没有遇到。
这是我的checkWinner方法代码:
public boolean checkWinner() {
for (int i=0;i<3;i++){
if ((gameBoard[i][0] == gameBoard[i][1]) && (gameBoard[i][1] == gameBoard[i][2])) { //check every row to find a match
System.out.println(currentMark + "wins!");
}
else if ((gameBoard[0][i] == gameBoard[1][i]) && (gameBoard[1][i] == gameBoard[2][i])) { //checks every column to find a match
System.out.println(currentMark + "wins!");
}
}
if ((gameBoard[0][0] == gameBoard[1][1]) && (gameBoard[1][1] == gameBoard[2][2])) { //checks first diagonal
System.out.println(currentMark + "wins!");
}
else if ((gameBoard[0][2] == gameBoard[1][1]) && (gameBoard[1][1] == gameBoard[2][0])) { //checks second diagonal
System.out.println(currentMark + "wins!");
}
else
System.out.println("Tie!");
return true;
}
这是我的游戏方法,每次用户进入移动后我都会使用checkWinner检查获胜者。
public void letsPlay() {
while (true) {
displayBoard();
gameOptions();
int choice = input.nextInt();
if (choice == 1) {
if (addMove(input.nextInt(),input.nextInt())) {
displayBoard();
checkWinner();
whoseTurn();
System.exit(0);
}
我不确定我的checkWinners方法是否应该是我的addMove方法的一部分...这是addMove
public boolean addMove(int row, int column) {
boolean nonacceptable = true;
while (nonacceptable) {
System.out.println("Which row and column would you like to enter your mark? Enter the row and column between 0 and 2 separated by a space.");
row = input.nextInt();
column = input.nextInt();
if ((row >= 0 && row <=2) && (column >= 0 && column <=2)) { //make sure user entered a number between 0 and 2
if (gameBoard[row][column] != ' ') {
System.out.println("Sorry, this position is not open!");
}
else {
gameBoard[row][column] = currentMark;
nonacceptable = false;
}
}
else
System.out.println("That position is not between 0 and 2!");
}
return nonacceptable;
}
如何将其合并到addMove方法中或更改它以使其作为自己的方法工作?
答案 0 :(得分:0)
看起来当用户输入有效答案时nonacceptable
设置为false,以便while(nonacceptable)
循环退出。但是你返回nonacceptable
(这是假的)意味着支票if (addMove())
不会通过(因此checkWinner
不会被调用)。您可以尝试将if
语句向下移动,如下所示:
addMove();
displayBoard();
if (checkWinner()) {
System.exit(0);
}
whoseTurn();
但是,只有在游戏获胜或并列时,您才需要将checkWinner
更改为true
,否则返回false
。