Java 2D数组OOB异常

时间:2019-06-09 02:49:36

标签: java arrays indexoutofboundsexception

我是Java编程的新手,我需要帮助了解为什么以下代码意图为解决Knight's Tour问题带来java.lang.ArrayIndexOutOfBoundsException

import java.util.*;
import java.lang.Math;

public class Main {

    public static void tourPrint(int[][] board){
        for (int c = 0; c < 8; c++){
            for (int d = 0; d < 8; d++) {
                System.out.print(board[c][d] + " ");
            }
            System.out.println();
        }
    }

    public static boolean tourCalculate(int[][] board, int[] row, int[] col, int r, int c, int num, int board_size){

        int newRow = 0;
        int newColumn = 0;

        if ((board[r][c] != 0) || (r < 0 || c < 0 || r >= board_size || c >= board_size)){
            return false;
        }
        board[r][c] = num;

        if(num == Math.pow(board_size, 2)){
            tourPrint(board);
            return true;
        }

        for (int z = 0; z <= board_size; z++){
            newRow = r + row[z];
            newColumn = c + col[z];
            if (tourCalculate(board, row, col, newRow, newColumn,num + 1, board_size)){
                return true;
            }
        }
        board[r][c] = 0;
        return false;
    }

    public static void main(String[] args) {

        int row_size = 0;
        int column_size = 0;
        int count = 0;
        final int board_size = 8;
        final int [] row = {2, 1, -1, -2, -2, -1, 1, 2};
        final int [] col = {1, 2, 2, 1, -1, -2, -2, -1};
        int[][] board = new int[board_size][board_size];

        for (int a = 0; a < 8; a++){
            for (int b = 0; b < 8; b++) {
                board[a][b] = 0;
            }
        }
        tourCalculate(board, row, col, row_size, column_size, count, board_size);
    }
}

我以前用C ++编写了相同的程序,其参数tourCalculate()void tour_print(int board[][board_size]...),而board_size作为全局变量。它似乎工作正常,但是在Java中,我无法在方括号中指定数组大小,而且我不确定是否将正确的数组尺寸传递给函数。有人可以帮忙指出导致错误的原因吗?

0 个答案:

没有答案