在 Java 的数组中用 for 循环替换值

Replacing values with for-loop in array in Java

我试图将数组的第一行和最后一行设置为 Java 中的 1,但只有数组中的第一个元素被更改。我的代码如下所示:

public void createArray(int height, int width){

        this.boardArray = new int [height][width];

        for (int i = 0; i < height; ++i){
            for (int j = 0; i < width; ++i){
                if (i == 0 || i == height){
                    this.boardArray[i][j] = 1;
                }
            }
        }
    }

但是当我这样做时,我得到了这个结果:

1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

但是我想不通为什么。

任何有关如何解决此问题的建议都将不胜感激,我是 Java 的新手,请多多包涵。

你的第二个循环中有一个简单的拼写错误:

for (int j = 0; i < width; ++i){

应该是

for (int j = 0; j < width; ++j){

此外,条件 i == height 永远不会是 true,因为在您显式测试的第一个循环中 i < height

当你只需要一个循环时,你可以避免使用两个循环:

for (int j = 0; j < width; ++j){
    this.boardArray[0][j] = 1;
    this.boardArray[height-1][j] = 1;
}

我认为正确的代码是这样的:

public void createArray(int height, int width){

    this.boardArray = new int [height][width];

    for (int i = 0; i < height; ++i){
        for (int j = 0; j < width; ++j){ //change i to j
            if (i == 0 || i == height - 1){ // also fill last row with ones
                this.boardArray[i][j] = 1;
            }
        }
    }
}

但是您不必遍历整个数组来访问第一行和最后一行。因此,另一种性能更好的方法如下所示:

public void createArray(int height, int width){

    this.boardArray = new int [height][width];
    if(height > 0) {
        Arrays.fill(this.boardArray[0], 1);
        if(height > 1) {
            Arrays.fill(this.boardArray[height - 1], 1);
        }
    }
}

最大的区别在于第一个解决方案的时间复杂度为 O(height*width),而第二个解决方案的时间复杂度仅为 O(width)。这是一个巨大的差异。

也许这个解决方案更具可读性:

Arrays.fill(boardArray[0], 1);
Arrays.fill(boardArray[height-1], 1);