1
所以我有這個程序,要求用戶的行數和列數,然後使它成棋盤板,但我的問題是,它只適用於奇數,如果用戶將投入9和9再次它將顯示一個方格板,但如果一個偶數被輸入它只是顯示白色和黑色java棋盤棋盤問題
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);
}
}
感謝您的幫助我終於解決了我的問題 – Isaiah