【发布时间】:2015-12-30 03:30:48
【问题描述】:
我没有收到任何编译错误,但肯定有逻辑错误,因为我的 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 方法中或更改它以使其作为自己的方法工作?
【问题讨论】:
-
在
if (addMove(input.nextInt(),input.nextInt()))行中,您调用了两次input.nextInt(),因此用户必须输入两个整数才能调用addMove。这是您期望的行为吗? -
@neuronaut 是导致所有问题的原因吗?我能把它改成什么?
-
我只会删除这些参数:
public boolean addMove()和if (addMove())。由于该函数已经提示用户并要求输入,因此您在调用该函数时不需要也要求输入(没有提示)。 -
你需要检查每一行的每一列,检查左右对角线
-
@neuronaut 好的,这样就解决了我两次输入的问题......但它仍然无法识别获胜者......你知道我该如何解决这个问题吗?