To nest is best
The structure that we've set up is called a "nested loop" because we have one iterative loop running inside another.
Inside the second loop, we're using j
as the iterator because i
is already in use. We're using the new
keyword to create a new instance of the Card
class, and we're adding it to the array at index aGrid[i,j]
.
Talk it through and it's not too tricky to understand:
The first time through the outside loop, we're at index
0
of our 2D Array.Then in the inner loop, we loop four times. Each time, we stuff a new card into the 2D Array called
aGrid
.Next, we do the main loop again. The outer index value
i
increases to 1.On to the inner loop, we cram four new cards into the empty. Now,
aGrid
contains 8 cards.We keep going until this whole thing plays out. At the end of the nested loop,
aGrid
is an array containing four arrays, and each of those arrays has four cards in it, for a total of 16 cards.
The reason why 2D Arrays are so handy is that we can easily access stuff inside...