如何才能使我的边界数组索引的右侧工作?

时间:2013-02-28 08:34:59

标签: 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();
    }

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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;

其他说明:

明智的做法是始终使用大括号括起循环块,如果条件:

//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!!! *****/