java—替换2d数组中的行和列

3npbholx  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(457)

我有一个二维数组:

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

我必须编写一个程序来检查数组中是否有0,如果有,则用0替换行和列,这样之后看起来像这样:

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

这是我目前的代码:

public class Run {

    public static void main(String[] args){
        //defining 2d array
        int[][] m = { {1,0,1,1}, 
                      {1,1,1,1},
                      {1,1,1,1},
                      {1,1,1,1}}; 
        int[][] newArray = zero(m);
        //looping through the array to get rows and columns for the array
        //rows
        for (int i = 0; i < m.length; i++) {
            //columns
            for (int j = 0; j < m[0].length; j++) { 
                //check if the integer is the last in the row
                if(j== m.length-1){
                    //print the rows and columns of the array(no space)
                    System.out.print(newArray[i][j]);
                }else{
                    //print the rows and columns of the array(w/ space)
                    System.out.print(newArray[i][j] + " ");
                }
            }
            //new line for the new row
        System.out.println("");
        }
    }

    //checks if there is a zero in the row
    public static int[][] zero(int[][] m) {
        //defining row length and column length
        int rows = m.length;
        int columns = m[0].length;
        int[][] tempArray = m;

        //looping through the array to get rows and columns
        //rows
        for (int i = 0; i < rows; i++) {
            //columns
            for (int j = 0; j < columns; j++) {
                //if the number is 0 loop through that row and column again and change everything to 0 
                if(m[i][j] == 0){
                    //columns in that row
                    for(int l = 0; l < rows; l++)
                    {
                        tempArray[l][j] = 0;
                    }
                    //rows in that column
                    for(int l = 0; l < columns; l++)
                    {
                        tempArray[i][l] = 0;
                    }
                }
            }
        }

        //returning the updated array
        return tempArray;
}

}

当我运行代码时,它返回:

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

但当我拿出其中一个:

//columns in that row
for(int l = 0; l < rows; l++)
{
    tempArray[l][j] = 0;
}

//rows in that column
for(int l = 0; l < rows; l++)
{
    tempArray[l][j] = 0;
}

它返回:

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

1 0 1 1
1 0 1 1
1 0 1 1
1 0 1 1
aurhwmvo

aurhwmvo1#

你在一个循环中检测到0,然后去修改数据,继续你的循环,现在会看到更多的零,所以设置更多的零。
您应该在发现0后中断,或者将检测和“重写”分开—首先执行所有检测,然后执行所有重写。

axr492tv

axr492tv2#

问题是线路

int[][] tempArray = m;

这使得 tempArray 以及 m 完全相同的示例,所以实际上只有一个矩阵。
相反,你应该这样做

int[][] tempArray = new int[rows][columns];
for (int i = 0; i < rows; i++)
    for (int j = 0; j < columns; j++)
        tempArray[i][j] = m[i][j];

相关问题