سؤال

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++;
            }
        }
    }
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

for(int row = 0; row < car.length; row++){
    for(int column = 0; column < car[row].length; column++){
        //print statement
        if(column == car[row].length - 1){
             System.out.println();
        }
    }
}

This implementation uses a pair of for loops, the outer one cares only for the length of the array in rows, the inner one cares only for the length of the row.

I do, however, find your single loop implementation interesting from a performance standpoint.

Ben

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top