trying to pass char array as an argument in java and getting Index error

Viewed 55

I'm trying to draw and initialize 2d array, when all my code is in main method there is no error but i split my code to methods and i had index error.

This is my method :

public static void initializeTable(char[][] table ) {

    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
             table[i][j] = 'S';   //this is line 90 where the error occurs i think.
        }
    }
}

How i use it in main :

    public class Cinema {
    public static int row, column,x,y;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char[][] table = new char[row][column];

        enterRowColumn();
        initializeTable(table); //line 15
    }
}

And error message :

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at cinema.Cinema.initializeTable(Cinema.java:90)
    at cinema.Cinema.main(Cinema.java:15)
2 Answers

Default value for primitive numbers is 0.

public static int row, column,x,y;

Those all are initialized as zeroes. Then you create array

char[][] table = new char[row][column];

before you assign other values, and array looks like char[0][0].

Move the array initialization after you assign values to row and column

You can avoid the ArrayIndexOutOfBoundsException by iterating using the array's state.

for (int i = 0 ; i < table.length ; ++i) {
  for (int j = 0 ; j < table[i].length ; ++j) {
    ...
  }
}

However, that still leaves you with the logical error of creating the table before knowing the dimensions. Basically change the order of these operations.

enterRowColumn()
char[][] table = new char[row][column];

p.s. kudos for using methods to do things rather than doing everything in your main method.

Related