java - 过滤掉一个数组
问题描述
我有一个布尔数组 [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,在进行此操作时输入错误。
解决方案
您必须保留两个不同的指针 - 一个用于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]]
推荐阅读
- node.js - React Router 不使用可变参数渲染组件
- swift - 如何在 Swift 中使用 Objc 在带有按钮的表格视图中打开视图控制器?
- c# - 如何使用存储过程从数据库中获取值并在 MessageBox C# 中显示?
- html - 实现自定义 CSS 技能栏
- android - 错误:无法解析“:app@debug/compileClasspath”的依赖关系:无法下载okhttp.jar (com.squareup.okhttp3:okhttp:4.3.1)
- python - 尝试在 xampp 中使用 python 和 mysql 时出错
- java - Minecraft mod 1.12.2 玻璃虫
- javascript - AudioWorkletNode 是否需要连接到 BaseAudioContext.destination?
- python - OperatorNotAllowedInGraphError:Graph 执行中不允许使用 tf.Tensor 作为 Python bool
- python - Python:TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”