java - 如何使边界数组索引的右侧正常工作?

标签 java arrays

我正在创建一个数组,其中一个和三个作为索引的值。我有两个代表我的边界。我已经编写了四个 for 循环来设置数组的边框。除了为右侧创建边框的 for 循环之外,它们似乎都可以工作。

value: 5

222222
213133
231133
211131
231331
222222


//Creates the border indexes for the cells represented by the value 2
    for (int top = 0; top < cells.length; top++)
        cells[0][top] = 2;

    for (int bottom = 0; bottom < cells.length; bottom++)
        cells[cells.length-1][bottom] = 2;

    for (int left = 0; left < cells.length; left++)
        cells[left][0] = 2;

    //for some reason, this code doesn't do anything
    for (int right = 0; right < cells.length; right++)
        cells[right][cells.length] = 2;


    // Creates the first generation of cells randomly
    for (int i = 1; i <m; i++)
    {

        for (int j = 1; j < m; j++)
        {   
            double CellCreate = Math.random();
            if (CellCreate > .5)
            {
                cells[i][j] = 1;

            }
            else
            {
                cells[i][j] = 3;

            }   
        }
    }

            //Prints the cells  
    for (int x = 0; x < cells.length;x++)
    {
        for (int y = 0; y < cells.length; y++)
        {
            System.out.print(cells[x][y]);
        }
        System.out.println();
    }

最佳答案

您忘记从 cells.length 中减去 1:

for (int right = 0; right < cells.length; right++)
    cells[right][cells.length-1] = 2;

关于java - 如何使边界数组索引的右侧正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15130902/

相关文章:

java - gwt 套接字连接

Java代理拦截请求

c++ - 在 C++ 中传递多维数组

java - 调用数组并返回不同数组的方法会给出无法解析 B 到变量错误

arrays - 修改 JSON 数组元素

java - java中连字符(-)有什么用

java - Eclipse 在 WAR 中导出 JAR

java - 评估html中的所有javascript以获得最终的html文档(java)

java - 我想写一个固定值的变量JSON

ruby - ruby 中的并行分配对于两个等效代码片段的工作方式不同