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.