2

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
  • could you post entire code Commented Jun 24, 2022 at 12:44
  • Well, row and column are not sync with the exact length from table. Either table has length equals to zero or table[j] has length equals to zero. Commented Jun 24, 2022 at 12:45

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

great advice, i understand now why most of programmers using the array's state. Can you briefly explain why you use plus sign before "i" ? I get used to use after "i" is there any significant difference between these? and thanks for p.s. :)
@toprakunal many moons ago there was an insignificant performance benefit to using pre-increment rather than post-increment, however, I don't know if that still holds. At this point it is just habit/personal-preference.

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.