Active ObjectsTopStyle guidelinesNumbingly boring

Numbingly boring

We can see examples where we can get interesting behavior through repeating the same instructions without depending on changes in the mouse position to make things interesting. Consider the following program which draws a set of railroad tracks one tie at a time.

    public void begin()
    {
        . . .
        tiePosition = 5;
   }
    
    public void onMouseClick( Location point )
    {
        if ( tiePosition < SCREEN_WIDTH ) {
            new FilledRect(tiePosition, TIE_TOP, TIE_WIDTH, TIE_LENGTH,
                           canvas);
            tiePosition = tiePosition + TIE_WIDTH + TIE_SPACING;
        }
    }

It is painful to have to click repeatedly to get the ties drawn. Instead we would like the computer to continue drawing ties while they are still on the screen. Java provides the while statement, or while loop, to perform repeated actions. Java includes other looping constructs that we will see later in the semester.

The syntax of a while statement is:

    while (condition)
    {
        ...
    }

Now we can draw all of our railroad ties using a while loop, WhileRailroad drawing all of the ties at once.

We talked about while loops where more than one variable changes. The example involved drawing a laundry basket


Active ObjectsTopStyle guidelinesNumbingly boring