user1906515
user1906515

Reputation:

ArrayIndexOutOfBoundsException - I dont understand why I am getting this error

What is wrong with my code? I am trying to pass two arguments(one for random seed and another for the and i get the array our of bounds exception error.. I dont understand what i am doing wrong.. I appreciate any help

import java.util.Random;

public class sparse {

    public static int size;
    public static int matrix[][] = new int[size][size];
    public static int seed;

    public static void main(String args[]) {

        seed = Integer.parseInt(args[0]);
        size = Integer.parseInt(args[1]);

        matrix = matrixGen();
    }

    public static int[][] matrixGen() {
        Random r = new Random(seed);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = r.nextInt(100);
            }
        }

        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                System.out.print(" " + matrix[i][j]);
            }
            System.out.println("  ");
        }

        return matrix;
    }
}

Upvotes: 1

Views: 123

Answers (3)

Giacomo Tesio
Giacomo Tesio

Reputation: 7210

The static fields seed and size have the default value (0) when you initialize the matrix field.

Thus matrix is a 0x0 array, without space for any element: any access will give such an exception.

To fix, you should set the matrix field in the main function, after arguments' parse.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

You get the error because you allocate the matrix at the time when the size is still zero:

public static int matrix[][] = new int[size][size]; // size is zero here

You need to remove the initialization from the declaration, and move it to the main(), after reading the size from args.

public static void main(String args[]) {
    seed = Integer.parseInt(args[0]);
    size = Integer.parseInt(args[1]);
    matrix = new int[size][size];
    matrix = matrixGen();
}

Upvotes: 4

niculare
niculare

Reputation: 3687

You must initialize the size of the matrix before allocating the space for it:

 public static int size = 30; // or whatever value do you want

Upvotes: 2

Related Questions