0

我正在创建一个以 1 和 3 作为索引值的数组。我有两个来代表我的边界。我已经编写了四个 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();
    }
4

2 回答 2

2

您忘记从 中减去 1 cells.length

for (int right = 0; right < cells.length; right++)
    cells[right][cells.length-1] = 2;
于 2013-02-28T08:37:21.183 回答
1

此外,这里还有一件事很有趣。原始循环没有失败ArrayOutOfBoundsException,因此很可能在声明您的数组时也出现了问题。如果正确定义了数组,我应该失败了。你也应该发布它......看来,你在数组中声明你的行有cells.length+1元素

否则,这是一个经典的循环结束问题,而不是cells.length

    cells[right][cells.length] = 2;

你应该使用cells.length-1

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

其他注意事项:

明智的做法是始终使用大括号括住循环块和 if 条件:

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

这样,您就不太可能陷入这样的“无循环”情况:

/**** BAD!!! *****/
for(...); // note the ; !!! That ends the loop block
    doSomething(); //this will be done only once!
/**** BAD!!! *****/
于 2013-02-28T08:37:44.013 回答