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

我有二维数组(测试)和需要删除行数的二维数组(删除行)。问题是我创建的循环在我尝试打印测试数组时没有结果。我需要创建不包括第 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 ) );

        }

    }

}


慕森王
浏览 156回答 1
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++) {&nbsp; &nbsp; if (j < removeRow.length && removeRow[j][0] == i) {&nbsp; &nbsp; &nbsp; &nbsp; j++;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; double[] row = test[i];&nbsp; &nbsp; &nbsp; &nbsp; rowsToKeep.add(row);&nbsp; &nbsp; }}test = new double[rowsToKeep.size()][];for (int i = 0; i < rowsToKeep.size(); i++) {&nbsp; &nbsp; test[i] = rowsToKeep.get(i);}System.out.println(Arrays.deepToString(test));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java