【发布时间】:2016-04-20 14:25:37
【问题描述】:
我创建了一个 for 循环来生成网格图。当我单击地图上的每个网格时,我会得到网格的 X 和 Y。当地图宽度大于地图长度时,一切都很好,但是当尝试创建长度大于地图的地图时,返回的 x 变为 y,而 y 变为 x。问题出在创建地图时的第二个 for 循环,但我无法弄清楚。
if(mapWidth>mapLength) {
for (int i = 0; i < mapWidth * mapLength; i++) {
y = i / mapLength;
for(int j=0; j<i+1; j++) {
x = j % mapLength;
}
GridPanel gb = new GridPanel(x, y);
list.add(gb);
mapPanel.add(gb);
}
} else if(mapWidth<mapLength) { //problematic map is created after this condition
for (int i = 0; i < mapWidth * mapLength; i++) {
x = i / mapLength;
for(int j=0; j < i+1; j++){
y = j % mapLength;
}
GridPanel gb = new GridPanel(x, y);
list.add(gb);
mapPanel.add(gb);
}
}
地图如下所示:
【问题讨论】:
-
为什么不只使用两个循环呢?
for (int x = 0; x < mapWidth; x++) { (int y = 0; y < mapLength; y++) { ... }} -
@flkes 很好,只会创建地图的 X 轴。