我正在尝试计算不均匀2D阵列中的元素数量。如果我尝试打印每个元素,它会抛出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));
}
答案 0 :(得分:1)
您必须手动检查。
例如:
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
答案 1 :(得分:0)
只检查null:
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)
continue;
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));
}