我正在尝试完成这个神奇的正方形项目,但是在填充正方形时,它引用的是空实例变量,而不是具有定义大小的实例变量,我似乎无法修复它。

在第22行显示为空错误。

谁能帮我这个?


public class MagicSquare {
    private int[][] magicSquare;

    public MagicSquare(int size){
        int[][] magicSquare = new int[size][size];
        fillSquare(size);
    }
    private void fillSquare(int size){
        int row = size - 1;
        int col = size / 2;
        magicSquare[row][col] = 1;

        for (int i = 2;i < size * size;++i){
            if (magicSquare[(1 + row) % size][(col + 1) % size] == 0){
                row = (1 + row) % size;
                col = (1 + col) % size;
            }
            else {
                row = ( row - 1 + size) % size;
            }
            magicSquare[row][col] = i;
        }
    }
    public void toString(int size){
        for (int i = 0; i < size;++i){
            for (int j = 0; j < size;++j){
                System.out.println(magicSquare[i][j]);
            }
        }

    }

}



最佳答案

不要在magicSquare中初始化int[][] magicSquare = new int[size][size];

超越了全球magicSquare实例,

您的代码应如下所示:

 public class MagicSquare {
        private int[][] magicSquare;

        public MagicSquare(int size){
            magicSquare = new int[size][size];
            fillSquare(size);
        }
        private void fillSquare(int size){
            int row = size - 1;
            int col = size / 2;
            magicSquare[row][col] = 1;

            for (int i = 2;i < size * size;++i){
                if (magicSquare[(1 + row) % size][(col + 1) % size] == 0){
                    row = (1 + row) % size;
                    col = (1 + col) % size;
                }
                else {
                    row = ( row - 1 + size) % size;
                }
                magicSquare[row][col] = i;
            }
        }
        public void toString(int size){
            for (int i = 0; i < size;++i){
                for (int j = 0; j < size;++j){
                    System.out.println(magicSquare[i][j]);
                }
            }

        }

    }

09-25 20:16