【问题标题】:using for loop to create gridmap使用 for 循环创建网格图
【发布时间】: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 &lt; mapWidth; x++) { (int y = 0; y &lt; mapLength; y++) { ... }}
  • @flkes 很好,只会创建地图的 X 轴。

标签: java algorithm for-loop


【解决方案1】:

好吧,也许我不太了解您的期望,但我认为您不必为mapWidthmapLength 的情况做一个特殊情况。 此外,除了使用 CPU 资源之外,我不明白您打算对嵌套循环做什么?

    for(int j=0; j<i+1; j++){
        x = j % mapLength;
    }

当它离开时,你将永远拥有x = i % mapLength

此外,正如 flkes 所建议的,您为什么不使用嵌套循环?

for (int y=0; y < mapLength; y++) {
    for(int x=0; x < mapWidth; x++){
       GridPanel gb = new GridPanel(x, y);
       list.add(gb);
       mapPanel.add(gb);
    }
}  

【讨论】:

    【解决方案2】:

    你能试试这个代码吗:

    for (int i = 0; i < mapWidth * mapLength; i++) {
        y = i / mapLength;
        x = i % mapLength;
    
        GridPanel gb = new GridPanel(x, y);
        list.add(gb);
        mapPanel.add(gb);
    }
    

    【讨论】:

    • 不幸的是,我可以点击从 x:0, y:0 到 x:3 ,x:3,之后其余的网格会出错。线程“AWT-EventQueue-0”中的异常 java.lang.IndexOutOfBoundsException:索引:90,大小:40
    • @PRCube 我认为您应该提供更多代码,因为我认为您提供的代码之外存在问题。
    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多