As usual, when faced with a tricky problem, we try and solve a simpler one first (getting into the mood).
Let's just try and create a row of beepers: Well try in manually first; take a concrete example. Say you want a row of beepers going from (2, 4) to (6, 4). Because we are repeating an instruction we feel there should be a loop.
First though let's write out the instructions in long hand.
// Create a world World space = new World(); // Add a row of beepers space.addBeeper(2, 4); space.addBeeper(3, 4); space.addBeeper(4, 4); space.addBeeper(5, 4); space.addBeeper(6, 4); |
You can see that the addBeeper instruction is executed 5 times. Can we use a loop here? Well if we had the following
// Create a world
World space = new World();
// Add a row of beepers
int i;
for(i = 0; i < 5; i++)
space.addBeeper(2, 4);
This would indeed call the addBeeper() method 5 times, but it would always add the beeper to the cell (2, 4). This is not what we want! We want the x-coordinate to change; we want to call the addBeeper method with the arguments
2 4 3 4 4 4 5 4 6 4
One way is to add i to the 2 each time through the loop:
// Add a row of beepers
int i;
for(i = 0; i < 5; i++)
space.addBeeper(2 + i, 4);
Another way of achieving the same effect is to create another variable which will cover the complete range:
// Add a row of beepers
int x;
for(x = 2; x <= 6; i++)
space.addBeeper(x, 4);
OK, so we've created a row of beepers; how do we create a rectangle of beepers?
We want to create a number of rows, one below the other. This could also be placed in a loop. In other words, one loop would be placed inside the other (nested loops).
Do we want each row to be the same? No, this time the y coordinate must change:
// Add a row of beepers
int x;
for(x = 2; x <= 6; i++)
space.addBeeper(x, 4);
Somehow you want a loop where the second argument (in this case 4) is not constant but is controlled by the loop variable.
Can you see how to do it? Best of luck.