gpt4 book ai didi

java - 从二维数组中删除空值以计算其元素数

转载 作者:行者123 更新时间:2023-11-30 11:21:01 26 4
gpt4 key购买 nike

我正在尝试计算不均匀二维数组中的元素数量。如果我尝试打印每个元素,它会抛出 null 异常。

1-如何让它忽略空条目?

2- 如何计算此矩阵中的元素数以创建一个等于此矩阵中元素数的新数组?

public static void main(String[] args) {

int[][] mat2 = { {1, 2, 3},
{4, 5},
{6},
null,
{},
{7,8}};

System.out.println("rows " + mat2.length);

for (int r = 0; r < mat2.length; r++) {
for (int c = 0; c < mat2[r].length; c++) {
int numElements = mat2[r][c];
System.out.println(numElements);
}
}

System.out.println("cols " +mat2[0].length);

//for (int[] row : mat2)
//System.out.println(Arrays.toString(row));

}

最佳答案

您必须手动检查它。

例如这个:

public static void main(String[] args) {
int[][] mat2 = {{1, 2, 3},
{4, 5},
{6},
null,
{},
{7, 8}};
System.out.println("rows " + mat2.length);
for (int r = 0; r < mat2.length; r++) {
if (mat2[r] == null) {
System.out.println("There is null");
} else {
for (int c = 0; c < mat2[r].length; c++) {
int numElements = mat2[r][c];
System.out.println(numElements);
}
}
}
System.out.println("cols " + mat2[0].length);
}

有这样的输出:

rows 6
1
2
3
4
5
6
There is null
7
8
cols 3

关于java - 从二维数组中删除空值以计算其元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22445071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com