java - 使用 for 循环创建网格图

标签 java algorithm for-loop

我创建了一个 for 循环来生成网格图。当我点击 map 上的每个网格时,我得到网格的 X 和 Y。本地图宽度大于 map 长度时,一切都很好,但是当尝试创建长度大于 with 的 map 时,返回的 x 变为 y,y 变为 x。问题出在创建 map 时的第二个 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);
    }
}

map 看起来像这样:

enter image description here enter image description here

最佳答案

好吧,也许我不太理解您的期望,但我认为您不必为 mapWidth<mapLength 的情况做一个特例。 此外,除了使用 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);
    }
}  

关于java - 使用 for 循环创建网格图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746906/

相关文章:

algorithm - 递归二叉树遍历的运行时复杂度

JavaScript For循环: Assignment to character not working

java - android:从非 Activity 类中使用openOrCreateDatabase

java - 从 Java 调用 Maven 目标

java - Jax-ws:在数据库中记录请求和响应

arrays - 连续无序数组中的不规则性

java - 正则表达式检查 URL

algorithm - 贪心算法按顺序查找潜在的加权事件?

javascript - 将 object.keys 复制到新对象

c++ - 为什么我得到一个无限循环(因素)?