Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the question I’ve to solve:

Write a class that, given a positive integer N, creates and returns a square matrix NxN made out of integers that displays the numbers from 1 to n^2 in a spiral

This is the code I’ve for it: 

public static int[][] spiral(int n) {

    int[][] res;

    int i,j;

    int num;

    int direction;

    /** variables initializzazion */

    res=new int[n][n];

    i=0;

    j=0;

    res[i][j]=1;

    direction=0;


 

    for(num=2; num<=n*n; num++) {

        direction = updateDirection(direction, i, j, n);

        if ((direction==1) || (direction==3))

            i=updateRow(i, direction);

        else

            j=updateColoumn(j, direction);

        res[i][j]=num;

    }

    return res;

}

When I run it, it gives me an ArrayIndexOutOfBoundException. Can anyone tell me what I’m doing wrong here?

1 Answer

0 votes
by (19.7k points)

When you try to set res[i][j] = 1 in the testSpiral method, you try to access the 1st element but it’s not present. So you have to start for int i=1 like below:

public static void testSpiral(){

    for(int n=1; n<=5; n++)

        System.out.println(Arrays.deepToString(spiral(n)));

}

Interested in Java? Check out this Java Certification by Intellipaat.   

Related questions

0 votes
1 answer
asked Apr 9, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Mar 14, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...