Don't worry, it is quite difficult at the beginning to understand about the array of arrays.
Ok, lets try to take this code
And make it look like this (note: row[*] and col[*] are illegal there - these are just for visualisation)
Now look at the two array declarations and initializations. Noticed, that these two are exactly the same, just different indentation and formatting basically. When you create array of arrays, I'd suggest you to use latter style (once again, just without those row and col).
When you have two nested loops, with an outer loop you iterate over the rows, with an inner over the columns OR in different words, outer loop iterates over the elements within the first deep level {...}, the inner loop over the elements within the second deep level {{...}}. That could sound confusing, read further.
Now what is happening when you iterating through an array with one loop?
Remember,
Arrays.toString() method prints whole array in one go. Earlier I mentioned that 2D arrays how you call them, in
Java these are array of arrays. So when you run your outer loop, you get array elements which are in between {...} first deep level brackets. In other words you get 3 elements which are also arrays:
{8, 3, 5, 7}
{2, 5, 0, 1}
{3, 9, 6, 4}
In order to get elements of those 3 arrays, you need another loop which is nested. You got that, but your problems started exactly there. Now the question is why?
Look carefully and you'll notice, that outer array (this is how i call it temporary here) has 3 elements in it (3 another arrays), BUT these 3 arrays, each of them has by 4 elements in it.
When you write
arr.length, you get length of
outer array (for that
outer someone will censure me), which is length 3, right?
Your inner loop has exactly the same as outer
arr.length, WHICH means - you'll iterate 1st element of array (which is also array {8, 3, 5, 7}) at most 3 times. BUT you need 4 here, get the idea where the problem is?
SOMEHOW, you need to amend inner for loop condition to iterate over the length of the {8, 3, 5, 7}.
Remember, at positions:
arr[0] there is an array element {8, 3, 5, 7} which is array itselfarr[1] there is array element {2, 5, 0, 1} which is array itselfarr[2] there is array element {3, 9, 6, 4} which is array itself
Look once again to your loops:
So, how do you need to amend one of the loops so you could iterate with outer loop over the
rows length and inner over the
columns length (one of those underlined you're doing correct already)?