简体   繁体   中英

Drawing a Checkerboard using nested for loops

I have a couple of questions regarding the use of nested for loops. In this example in the book it uses nested for loops to draw a typical checkerboard.

1) Is my understanding correct when I assume the code below says the sequence of drawing the checkerboard squares will be vertically down from left to right until the entire checkerboard is drawn?

2) I'm have some questions about the purpose of double x, and double y inside the inner most for loop. Are they being calculated for the purpose of spacing one square to the next? Can you expand on the purpose of double x and double y and what occurs each cycle of one loop?

import acm.program.*;
import acm.graphics.*;




public class checkerBoard extends GraphicsProgram{
    public void run(){


        double sqSize = getHeight() / N_ROWS;
        for ( int i = 0; i < N_ROWS; i++){
            for (int j = 0; j < N_COLUMNS; j++){
                double x = j * sqSize;
                double y = i * sqSize;

                GRect rect = new GRect(x, y, sqSize, sqSize);
                rect.setFilled((i+ j) % 2 !=0);
                add(rect);

            }

        }

    }


    private static final int N_ROWS = 8;
    private static final int N_COLUMNS = 8;


}

1) Is my understanding correct when I assume the code below says the sequence of drawing the checkerboard squares will be vertically down from left to right until the entire checkerboard is drawn?

This is correct. Row by row, left to right, top to bottom.

2) I'm have some questions about the purpose of double x, and double y inside the inner most for loop. Are they being calculated for the purpose of spacing one square to the next? Can you expand on the purpose of double x and double y and what occurs each cycle of one loop?

They are the coordinates of the location where to draw the next square. Specifically, they are the coordinate for the upper left part of the square. You can figure out the start points for all squares by simply multiplying by the width of the squares, as they have done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM