Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading