[英]Replacing rows and columns in a 2d array
我有一个二维数组:
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
问题是线
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];
您在循环中检测到0,然后去修改数据并继续循环,现在循环将看到更多的零,因此设置了更多的零。
一旦发现0,就应该中断,或者将检测与“重写”分开-先进行所有检测,然后再进行所有重写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.