简体   繁体   English

java Checker board问题

[英]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 所以我有这个程序,要求用户提供多个行和列,然后使其成为一个棋盘但我的问题是,它只适用于奇数,如果用户要再次放入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);
    } 
}

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 . 这里有一个完整的例子。

图片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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