-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?

6
  • 1
    Du you run your program with atleast 4 Parameters? Arrays are Zero based! Commented Nov 14, 2018 at 14:02
  • wdym parameters? Commented Nov 14, 2018 at 14:06
  • how are you starting your program...e.g. java MyClass ..., your line that has args[3] is expecting at least 4 things after the class name. Commented Nov 14, 2018 at 14:11
  • only the public one Commented Nov 14, 2018 at 14:22
  • stackoverflow.com/questions/40490628/… Commented Nov 14, 2018 at 15:20

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

how can u make it like 8 1 6 and 4 9 2 switched places
I ran your program passing 4 arguments in console. It is given above result. Updated my comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.