[英]How to properly check if two jagged arrays are the same size?
我無法檢查兩個鋸齒狀的 java arrays 的大小是否相同。 我的 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.
我嘗試執行代碼以查看返回的 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;
}
如果兩個數組都是 null 或大小相同,我希望 output 為真,否則為假。 我收到來自自動評分器的錯誤,說明如下:
java.lang.AssertionError:不正確的結果:預期[false]但發現[true]
我應該調整什么以確保返回的值具有正確的值?
嘗試這個。
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.