Search code examples
javaarraysmethodsindexingbounds

printing array out of bounds java


i have an array of objects looking like this:

1: [volvo, 200] , [jaguar, 900]
2: [bmw, 300]
3: [skoda, 100] , [(no input)] , [(no input)]


this is my method to print only the areas with value (with some formating inside but it is not the issue). get an out of bound error... what do i need to do? thank you!

        public static void printMat(Car[][] carMat){
        int row = 0;
        int column = 0;
        while ((carMat[row][column] != null)){
            System.out.printf("( %-8s : %,9d )", carMat[row][column].getName(), carMat[row][column].getPrice());
            if (column == carMat[row].length - 1){
                System.out.print("\n");
                row++;
                column = 0;
            } else {
                column++;
            }
        }
    }

Solution

  • You have checked if you are going off the end of the current row, which is good, but you haven't checked if you have run out of rows.

    After row++, add in a check to see if row has gone off the end of the carMat array.

    if (row >= carMat.length)
        break;
    

    That assumes that you have at least one row. You may want to check if you have at least one row before you even enter the while loop.