首页 > 解决方案 > 过滤掉一个数组

问题描述

我有一个布尔数组 [true,false,false,true,true] 并想使用它拆分一个二维数组。我尝试做的是

public static void sorting(boolean[] test, String[][] arr)
   {
       int counter = 0;
       //finds how many people passed
       for(int z = 0; z < arr.length; z++)
       {
           if (test[z] != false)
               counter++;
               
       }
       String[][] passed = new String[counter][2];
       //tests for which people had Passed and copies it over
       for(int x = 0; x < passed.length; x++)
       {
           for(int y = 0; y < passed[x].length; y++)
           if(arr[x] != false)
               passed[x][y] = arr[x][y];
       }
       example2dArrayPrint(passed);
   }

我的输入是

Bob A
Fred F
Larry F
John C
Tom B

输出将是

Bob A
John C
Tom B

我不明白为什么这不能正确排序。编辑

两个数组之间的关系是,如果 test[0] == true,arr[0][0] 和 arr[0][1] 的那部分将被放入新传递的数组中,false 将被跳过。
编辑2

从 3 更改为 2,在进行此操作时输入错误。

标签: javaarrays

解决方案


您必须保留两个不同的指针 - 一个用于passed数组中的当前位置,另一个用于输入arr。尝试这个:

public static void sorting(boolean[] test, String[][] arr) {
    int counter = 0;
    //finds how many people passed
    for (int z = 0; z < arr.length; z++) {
        if (test[z])
            counter++;

    }
    String[][] passed = new String[counter][2];
    int i = 0;
    //tests for which people had Passed and copies it over
    for (int x = 0; x < arr.length; x++) {
        if (test[x]) {
            for (int y = 0; y < 2; y++) {
                passed[i][y] = arr[x][y];
            }
            i++;
        }
    }

    example2dArrayPrint(passed);
}

输出:

[[Bob, A], [John, C], [Tom, B]]

推荐阅读