【发布时间】:2016-06-28 03:33:36
【问题描述】:
TicTacToe 程序中的 checkTie 方法不起作用,导致数组越界,我不明白为什么。
运行此代码将打印棋盘并允许游戏运行,直到有人获胜,或者还剩 3 个 _,然后游戏结束。
我不确定为什么会发生这种情况,我相信这与我的checkTie for 循环有关。此外,如果出现平局,要么什么都没有发生,要么发生数组越界。
import java.util.Scanner;
public class TicTac {
public static int row, col;
public static Scanner scan = new Scanner(System.in);
public static char[][] board = new char[3][3];
public static char turn = 'X';
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '_';
}
}
Play();
}
public static boolean Play() {
boolean playing = true;
PrintBoard();
while (playing) {
System.out.println();
System.out.print("Please enter row: ");
row = scan.nextInt() - 1;
System.out.print("Please enter column: ");
col = scan.nextInt() - 1;
board[row][col] = turn;
if (GameOver(row, col)) {
playing = false;
System.out.println("Game Over! Player " + turn + " wins!");
**I feel like this code below is where the problem is**
if (checkTie(board)) {
System.out.println("Tie Game!");
return true;
}
}
PrintBoard();
if (turn == 'X')
turn = '0';
else
turn = 'X';
}
return false;
}
public static void PrintBoard() {
for (int i = 0; i < 3; i++) {
System.out.println();
for (int j = 0; j < 3; j++) {
if (j == 0)
System.out.print("| ");
System.out.print(board[i][j] + " | ");
}
}
System.out.println();
}
public static boolean GameOver(int rMove, int cMove) {
// Check if perpendicular victory
if (board[0][cMove] == board[1][cMove] && board[0][cMove] == board[2][cMove])
return true;
if (board[rMove][0] == board[rMove][1] && board[rMove][0] == board[rMove][2])
return true;
// Check Diagonal Victory
if (board[0][2] == board[1][1] && board[0][0] == board[2][2] && board[1][1] != '_')
return true;
if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[1][1] != '_')
return true;
return false;
}
这是查看比赛结果是否平局的方法。
public static boolean checkTie(char[][] board) {
int spacesLeft = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '_') {
spacesLeft++;
}
}
}
if (spacesLeft == 0) {
return true;
} else {
return false;
}
}
}
【问题讨论】:
-
告诉我们您用来使程序崩溃的确切输入。就目前而言,代码没有表现出您描述的行为。在任何情况下,Java 都会告诉您它失败的 exact 行,以便您从那里开始调查。
-
如果您收到 IndexOutOfBoundsException 异常,您应该会看到详细的堆栈跟踪,它会毫不含糊地告诉您发生的确切位置——无需“感觉”。
-
哦,对不起,我修复了OutOfBoundsException,只是游戏没有执行checkTie方法并且没有结束是问题
标签: java arrays for-loop methods