如果 A 中的所有元素都在 B 中找到,我希望回傳 true,否則回傳 false。目前,我已經撰寫了下面的代碼,但該函式似乎只回傳 false。
public static boolean con(int[] a, int[] b) {
if (a == null || a.length == 0) {
return false;
}else if (b == null || b.length == 0) {
return false;
}
for (int i = 0; i < a.length; i )
{
for (int j = i 1; j < b.length;j )
{
if (a[i] == (b[j])) {
return true;
}
}
}
return false;
}
uj5u.com熱心網友回復:
使用索引編程時很容易出錯。幸運的是,在這種情況下,不需要這樣做:
public static boolean con(int[] a, int[] b) {
loop: for (int ai : a) {
for (int bi : b) {
if (ai == bi) {
continue loop;
}
}
return false;
}
return true;
}
始終使用語言的優點,而不是缺點。
uj5u.com熱心網友回復:
正如注釋中指出的那樣,您的代碼中有幾個問題導致您的代碼回傳 false,但是,另一個問題是您的 return true if a[i] == (b[j])which will be true 并且如果陣列中的第一個元素會導致回傳無論陣列的其余部分如何以及是否匹配,都是匹配的。
這是一個作業版本,其中包含有助于解釋更改內容的注釋:
public static boolean con(int[] a, int[] b) {
//Use a flag to track if the integers are found
Boolean flag = true;
//return false for null or 0 length
if (a == null || a.length == 0 || b == null || b.length == 0) {
return false;
}
//Check integers
for (int i = 0; i < a.length; i ){
//Use an inner flag to track each integer
Boolean innerFlag = false;
//Start the inner loop from 0 and incriment it
//Only use j = i if you need the integers to be in order?
for (int j = 0; j < b.length; j ){
if (a[i] == (b[j])) {
//we can not return from the method until all elements are checked
//so set the flag instead and break so the next element can be checked
innerFlag = true;
break;
}
}
//if an element does not exist we can set the flag false and break and return immediatly
if (innerFlag == false){
flag = false;
break;
}
}
return flag;
}
uj5u.com熱心網友回復:
為什么你使用 int j = i 1 而不僅僅是 j 將陣列開頭的所有 b 與 j = 0 進行比較......無論如何,如果你改變它并用兩個相等的填充陣列測驗它,它將在第一個元素,如果陣列不同,當兩者重合時會給你 true,但你沒有將結果存盤在任何地方,我認為你可以做的是添加一個長度為 a 的計數器:
for (int i = 0; i < a.length; i ) {
for (int j = 0; j < b.length; j ) {
if (a[i] == (b[j])) {
count--;
if(count == 0)
return true;
}
它有點作業,徹底測驗并告訴我。
uj5u.com熱心網友回復:
如果你真的想手動做,你可以使用這樣的東西:
private static boolean containsAll(Integer[] arrayA, Integer[] arrayB) {
Set<Integer> matches = new HashSet<>();
boolean containsAll = false;
for (int i = 0; i < arrayA.length; i ) {
for (int j = 0; j < arrayB.length; j ) {
if (arrayA[i] == arrayB[j]) {
matches.add(arrayA[i]);
}
}
}
if (matches.size() == arrayA.length) {
containsAll = true;
}
return containsAll;
}
由于 aset只能存盤唯一值,即使arrayB有重復的元素,它仍然可以作業。arrayA但是,如果有重復的元素,它將不起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444845.html
上一篇:如何將物件陣列組合成一個物件,然后根據索引上的條件在該陣列中創建另一個物件
下一篇:串列/陣列的奇怪行為
