CodeHS often uses a custom GraphicsProgram class. Here is the correct, working, fixed code for 9.1.6 Checkerboard (v1) in Java:
import acm.graphics.*; import acm.program.*; import java.awt.*;public class Checkerboard extends GraphicsProgram 916 checkerboard v1 codehs fixed
private static final int SQUARE_SIZE = 50; private static final int ROWS = 8; private static final int COLUMNS = 8; public void run() for (int row = 0; row < ROWS; row++) for (int col = 0; col < COLUMNS; col++) int x = col * SQUARE_SIZE; int y = row * SQUARE_SIZE; GRect square = new GRect(x, y, SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); // Checkerboard logic: alternate color based on (row + col) % 2 if ((row + col) % 2 == 0) square.setColor(Color.RED); // or Color.GRAY else square.setColor(Color.BLACK); add(square);
Create a 8x8 checkerboard using a loop. The checkerboard should have alternating black and white squares. CodeHS often uses a custom GraphicsProgram class
(column * 50, row * 50) with size 50x50If you would like to create checkerboard you may use following code: Create a 8x8 checkerboard using a loop
import javax.swing.*;
import java.awt.*;
public class Checkerboard extends JPanel
public Checkerboard()
setPreferredSize(new Dimension(800, 800));
setBackground(Color.WHITE);
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
int rows = 8;
int cols = 8;
int squareSize = 100;
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
Color color = (row + col) % 2 == 0 ? Color.BLACK : Color.WHITE;
g.setColor(color);
g.fillRect(col * squareSize, row * squareSize, squareSize, squareSize);
public static void main(String[] args)
JFrame frame = new JFrame("Checkerboard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Checkerboard());
frame.pack();
frame.setVisible(true);
| Mistake | Consequence | Fix |
|---------|------------|-----|
| (col % 2 == 0) only | Stripes, not checkerboard | Use (row + col) % 2 |
| Using setFillColor instead of setColor | Square remains unfilled | Use setColor OR both setFilled(true) and setFillColor |
| Forgetting setFilled(true) | Transparent squares | Add square.setFilled(true); |
| Incorrect loop bounds (e.g., row <= ROWS) | ArrayIndexOutOfBounds or extra row | Use < ROWS |