通过循环从数组中删除多行

时间:2018-11-11 16:06:19

标签: java arrays

我有2d数组(测试),并且需要删除2d的行数数组(删除Row)。问题是我创建的循环导致在尝试打印测试阵列时没有结果。我需要创建不包含行0、1、3、4的新矩阵。

如何在while循环之外访问新数组?

import java.util.ArrayList;
import java.util.Arrays;

public class remove
{
    public static void main( String[] args )
    {
        double[][] test = { { 100 }, { 200 }, { 300 }, { 400 }, { 500 }, { 600 }, { 700 },
                           { 800 }, { 900 }, { 1000 } };

        int[][] removeRow = { { 0 }, { 1 }, { 3 }, { 4 }, };

        int reduce = 1;
        int r = 0;
        while ( reduce == 0 )
        {
            ArrayList<double[]> rowsToKeep = new ArrayList<double[]>( test.length );
            for ( int i = 0; i < test.length; i++ )
            {
                if ( i != removeRow[0][0] - r )
                {
                    double[] row = test[i];
                    rowsToKeep.add( row );
                }
            }
            r++;
            test = new double[rowsToKeep.size()][];
            for ( int i = 0; i < rowsToKeep.size(); i++ )
            {
                test[i] = rowsToKeep.get( i );
            }
            reduce = removeRow.length - r;
            r = r++;
            System.out.println( Arrays.deepToString( test ) );
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我对您的算法做了些改动。在if (j < removeRow.length && removeRow[j][0] == i)中,我们找到要删除的行,而没有做任何事情,只是增加j,否则在else块中,将行添加到rowsToKeep列表中。

尝试一下:

double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000} };
int[][] removeRow = { {0}, {1}, {3}, {4} };
int j = 0;
List<double[]> rowsToKeep = new ArrayList<>(test.length);
for (int i = 0; i < test.length; i++) {
    if (j < removeRow.length && removeRow[j][0] == i) {
        j++;
    } else {
        double[] row = test[i];
        rowsToKeep.add(row);
    }
}
test = new double[rowsToKeep.size()][];
for (int i = 0; i < rowsToKeep.size(); i++) {
    test[i] = rowsToKeep.get(i);
}
System.out.println(Arrays.deepToString(test));