[英]How do I remove a specific row and a specific column from a 2D Array in Java?
If I have a method that accepts an int[][] , a row number to remove, and a column number to remove, how would I remove that specific row and column from the Array and return the new reduced Array? 如果我有一个接受int [] []的方法,要删除的行号和要删除的列号,我将如何从Array中删除该特定的行和列并返回新的简化数组?
I want to do it by taking everything except the row/column I want to remove and then putting it into two temporary ArrayLists, then constructing a new Array to return from the values in the two Arrays. 我想通过除了我要删除的行/列之外的所有内容,然后将它放入两个临时的ArrayLists,然后构造一个新的Array以从两个Arrays中的值返回来实现它。 I think I can remove a specific row just fine, however I don't know how to remove the column as well. 我想我可以删除一个特定的行,但我不知道如何删除列。
I think the best approach is create a new array of 我认为最好的方法是创建一个新的数组
int[xsize-1][ysize-1]
Have a nested for loop to copy from source array to destination. 有一个嵌套的for循环从源数组复制到目标。 And skip for a specific i and j 并跳过特定的i和j
static void TestFunction()
{
int rows = 5;
int columns = 6;
int sourcearr[][] = new int[rows][columns];
int destinationarr[][] = new int[rows-1][columns-1];
int REMOVE_ROW = 2;
int REMOVE_COLUMN = 3;
int p = 0;
for( int i = 0; i < rows; ++i)
{
if ( i == REMOVE_ROW)
continue;
int q = 0;
for( int j = 0; j < columns; ++j)
{
if ( j == REMOVE_COLUMN)
continue;
destinationarr[p][q] = sourcearr[i][j];
++q;
}
++p;
}
}
I'm trying to remove both 3 in two columns, under the index 2, how to achieve it? 我试图删除索引2下的两列中的3个,如何实现它?
public class For_petlja {
public static void main(String[] args) {
int[][] niz = {
{9, 2, 3, 6, 7},
{4, 7, 3, 5, 1}
};
int j;
for (int i = 0; i < niz.length; i++) {
for (j = 0; j < niz[i].length; j++) {
if (i == 2) {
continue;
}
} // for 'j'
System.out.println(Arrays.toString(niz[j]));
} // for 'i'
} // main method.
} // class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.