gpt4 book ai didi

java - 如何避免在我的矩阵总和中出现 NullPointerException?

转载 作者:行者123 更新时间:2023-11-29 05:02:38 28 4
gpt4 key购买 nike

我想检查任何矩阵中每一行的总和是否相等。我应该如何重写它以避免 NPE?

我可以让它适用于像 int[][] a = {{1,2,3}, {4,5,6}} 这样的“普通”矩阵,但我想要它即使在使用 null 和空矩阵进行测试时也能正常工作。

public static boolean allRowSumsEqual(int[][] m) {
boolean a = false;
int x = 0;
int total = rowSum(m[0]);

for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
x += m[i][j];
}
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}

public static int rowSum(int[] v) {
int vSum = 0;
for (int i = 0; i < v.length; i++) {
vSum += v[i];
}
return vSum;
}

最佳答案

如您所说,这对大多数矩阵都有效。有几个地方我可能会检查是否为 null,请参阅下面修改后的代码:

public static boolean allRowSumsEqual(int[][] m){
if(m == null) return true;
if(m.length == 0) return true;

boolean a = false;
int x = 0;
int total = rowSum(m[0]);

for (int i = 1; i < m.length; i++){
// You can use your own function instead of the inner for loop
x = rowSum(m[i]);
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}

public static int rowSum(int[] v){
int vSum = 0;

// Assume a null row has sum 0
if(v == null) return 0;

for (int i = 0 ; i < v.length ; i++){
vSum += v[i];
}
return vSum;
}

关于java - 如何避免在我的矩阵总和中出现 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31549383/

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