[英]How to properly check if two jagged arrays are the same size?
I am having trouble checking if two jagged java arrays are the same size.我无法检查两个锯齿状的 java arrays 的大小是否相同。 My function isn't returning the correct result.
我的 function 没有返回正确的结果。 The hw problem I'm working on states that the function should return true if both arrays are null or are the same size, and should return false if the only one of the array's is null or if they have a different size.
The hw problem I'm working on states that the function should return true if both arrays are null or are the same size, and should return false if the only one of the array's is null or if they have a different size.
I have tried executing the code to see what boolean value is returned, however the console outputs nothing.我尝试执行代码以查看返回的 boolean 值,但是控制台什么也没输出。
static boolean arraySameSize(int[][] one, int[][] two) {
boolean value = false;
if (one == null && two == null) {
value = true;
} else if ((one == null && two != null) || (two == null && one != null)) {
value = false;
} else {
int count = 0;
int count2 = 0;
for (int i = 0; i < one.length; i++) {
for (int j = 0; j < one[i].length; j++) {
count++;
}
}
for (int i = 0; i < two.length; i++) {
for (int j = 0; j < two[i].length; j++) {
count2++;
}
}
if (count == count2) {
value = true;
} else {
value = false;
}
}
return value;
}
I expect the output to be true if both array's are null or are the same size, false otherwise.如果两个数组都是 null 或大小相同,我希望 output 为真,否则为假。 I am getting an error from the auto-grader stating the following:
我收到来自自动评分器的错误,说明如下:
java.lang.AssertionError: Incorrect result: expected [false] but found [true] java.lang.AssertionError:不正确的结果:预期[false]但发现[true]
What should I adjust to ensure that value has the correct value when it's returned?我应该调整什么以确保返回的值具有正确的值?
try this.尝试这个。
static boolean arraySameSize(int[][] one, int[][] two) {
if (one == null && two == null) return true;
if (one == null || two == null) return false;
if (one.length != two.length) return false;
for (int i = 0, size = one.length; i < size; ++i) {
int[] oneRow = one[i];
int[] twoRow = two[i];
if (oneRow == null && twoRow == null) continue;
if (oneRow == null || twoRow == null) return false;
if (oneRow.length != twoRow.length) return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.