简体   繁体   中英

java Checker board issues

so i have this program that asks a user for a number of rows and columns and then makes it into a checker board but my issue is that it only works with odd numbers like if the user was to put in 9 and 9 again it would display a checkered board but if a even number is inputted it just shows columns of white and black

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);
    } 
}

Your example identifies even numbers in a single loop. Instead, use nested loops to identify alternating tiles:

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);
        }
    }
}

A complete example is seen here .

图片

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