9.1.7 Checkerboard V2 Answers Official

Allow the user to input the number of rows and columns. The program should dynamically adjust and still produce a perfect checkerboard.

import java.awt.Color;
import acm.graphics.*;
import acm.program.*;

public class CheckerboardV2 extends GraphicsProgram 9.1.7 checkerboard v2 answers

private static final int ROWS = 8;
private static final int COLS = 8;
private static final int SQUARE_SIZE = 50;
public void run() 
    // Create a 2D array to store colors
    Color[][] checkerboard = new Color[ROWS][COLS];
// Fill the array with alternating colors
    for (int row = 0; row < ROWS; row++) 
        for (int col = 0; col < COLS; col++) 
            if ((row + col) % 2 == 0) 
                checkerboard[row][col] = Color.RED;
             else 
                checkerboard[row][col] = Color.BLACK;
// Draw the checkerboard using the stored colors
    for (int row = 0; row < ROWS; row++) 
        for (int col = 0; col < COLS; col++) 
            int x = col * SQUARE_SIZE;
            int y = row * SQUARE_SIZE;
            GRect square = new GRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
            square.setFilled(true);
            square.setFillColor(checkerboard[row][col]);
            add(square);

Add a method that randomly selects two contrasting colors and builds the board using them instead of hard-coded RED and BLACK. Allow the user to input the number of rows and columns

Given an (n \times n) checkerboard, how many ways can you place (n) checkers such that no two checkers are on the same row or column? Add a method that randomly selects two contrasting

To make each square stand out, add:

square.setBorderColor(Color.WHITE);