java 棋盘问题

java Checker board issues

所以我有这个程序要求用户输入一些行和列,然后将其变成棋盘,但我的问题是它只适用于奇数,比如用户输入 9 和9 再次显示方格板,但如果输入偶数,它只显示白色和黑色的列

import javax.swing.*;
import java.awt.*;

public class Checkers {

    public static void main(String[] args) {
        JFrame theGUI = new JFrame();
        theGUI.setTitle("Checkers");
        String inputStr = JOptionPane.showInputDialog("Number of rows");
        if (inputStr == null) return;
        int rows = Integer.parseInt(inputStr);
        inputStr = JOptionPane.showInputDialog("Number of Columns");
        if (inputStr == null) return;
        int cols = Integer.parseInt(inputStr);
        theGUI.setSize(cols * 50 , rows * 50);
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container pane = theGUI.getContentPane();
        pane.setLayout(new GridLayout(rows, cols));
        for (int i = 1; i <= rows * cols ;i ++) {
            if(i % 2 == 0){
              ColorPanel panel = new ColorPanel(Color.white);
              pane.add(panel);
            }else{
                ColorPanel panel = new ColorPanel(Color.black);
                pane.add(panel);
            }
        }
        theGUI.setVisible(true);
    } 
}

您的示例在单个循环中识别偶数。相反,使用嵌套循环来识别 交替 个图块:

g.setColor(Color.lightGray);
…
for (int row = 0; row < h; row++) {
    for (int col = 0; col < w; col++) {
        if ((row + col) % 2 == 0) {
            g.fillRect(col * TILE, row * TILE, TILE, TILE);
        }
    }
}

看到完整的例子here