-1

I want to program a Magic Square wherein the utilization of arrays is at place but when i want to run it, it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at MagicSquare.main(MagicSquare.java:6) What should I do? It would show

4   9   2        7 1 6
3   5   7  not   3 5 7
8   1   6        4 9 2 



public static void main(String[] args) { 
    Scanner input = new Scanner (System.in);

    int n = Integer.parseInt(args[3]);
    if (n % 2 == 0) throw new RuntimeException("n must be odd");

    int[][] magic = new int[n][n];

    int row = n-1;
    int col = n/2;
    magic[row][col] = 1;


    for (int i = 2; i <= n*n; i++) {
        if (magic[(row + 1) % n][(col + 1) % n] == 0) {
            row = (row + 1) % n;
            col = (col + 1) % n;
        }
        else {
            row = (row - 1 + n) % n;

        }
        magic[row][col] = i;
    }


    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (magic[i][j] < 10)  System.out.print(" ");  
            if (magic[i][j] < 100) System.out.print(" ");  
            System.out.print(magic[i][j] + " ");
        }
        System.out.println();
    }

}

What else should I add or take away from this program?

pat
  • 53
  • 7

1 Answers1

0

According to your program, need to provide 4 arguments when running. ex: If class name is Test:

java Test 1 1 1 3

Result:

  4   9   2
  3   5   7
  8   1   6