我正在创建一个数组,其中一个和三个作为索引的值。我有两个代表我的边界。我已经编写了四个 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/