Talking to ActiveObjectsTopSummary of classesMore on loops

More on loops

Now that we have seen how important loops are in ActiveObject's, we would like to go back and discuss more complex loops. The first program generates a picture of a scarf wherever the user clicks.

The key to developing programs involving nested loops is to understand first what the outer loop is doing (going through successive rows) and what the inner loop is drawing (drawing all circles of an inner loop. We can think of the general structure as:

    while (rowNum < MAX_ROWS) {
       draw new row
       rowNum = rowNum+1
       shift y coordinate of new row
    }

Drawing a new row now requires only initializing the starting x coordinate and a while loop to draw all of the circles.

Each time we start a new row, there are a number of things that we will need to take care of:

  1. We need to reset the value of x so that we start drawing at the beginning of the row rather than where we left off.
  2. We to increase the value of y so that rows won't be drawn on top of each other.
  3. We need to reset numCols back to 0 so that it will keep the correct count when we restart drawing a row.
  4. We need to bump up numRows each time through.

Suppose we wish to design a class to draw an American flag.

New things appearing in the code:

  1. We use "++" to indicate that a variable's value should be incremented by one. Thus in drawStripes, each time through the loop, stripeNum++ increases the value of strikeNum by one. In general, x++; abbreviates x = x+1; if x is an int variable.
  2. Private methods: The methods drawStripes and drawStars are called from inside the Flag constructor. They are not designed to be accessible from outside the class. They are designed only to be useful in breaking down the constructor into easier to understand pieces. drawStripes, is especially useful because it allows us to avoid duplicating code. Notice that it is used twice inside the constructor. Once to draw short stripes, and once to draw long stripes. Because we provide different parameters to it each time, it produces different results. If we did not use this private method, we would have to repeat the code in the method twice, once for each collection of values of the parameters.

Old, but interesting, things in the code include the nested while loop in the drawStars method as well as the fact that several items are changing each time through the while loops. Notice that in the outer while loop in drawStars, we must reinitialize both col and x each time through the loop.


Talking to ActiveObjectsTopSummary of classesMore on loops