![](/img/trans.png)
[英]Matching Products in an Array list against another Array list for similar products
[英]Checking an array list against another array list
這是拼寫檢查器中的一種方法。 正如標題所解釋的,僅當在父數組中找到所有添加到arraylist的單詞時,才應返回true。 否則,它將返回一個假值。 我已經為此戰斗了幾個小時,這就是我目前的情況...
/**
* This method returns true if (and only if) all words in the
* given wordList are found in the dictionary.
*/
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size(); index++)
{
if(words.contains(!wordList.contains(index)))
{
result = false;
}
result = true;
}
return result;
}
我真正需要的只是一種證明是或否的方法,但我迷路了。 請嘗試使用給出的代碼,因為這是教該代碼的練習。 謝謝!
您的問題在這里:
if(words.contains(!wordList.contains(index)))
!wordList.contains(index)
是一個布爾表達式,因此它總是計算為true
或false
。 因此,您實際上是在檢查words
列表中包含的是真還是假,而不是您想要的單詞。 用if(!words.contains(wordList.get(index))
替換它,以檢查是否在詞典中找到了當前單詞。
重復:我建議一個解決方案如下wordList
,如果它在字典中的一字一句,並為每個字檢查。 如果不是這樣,請立即返回false。 如果到達循環末尾,則返回true。
這可能是另一種解決方案:
public static boolean allKnown(List<String> parent, List<String> child) {
List<String> temp = new ArrayList<String>(child);
temp.removeAll(parent);
return temp.isEmpty();
}
例如:
List<String> parent = Arrays.asList("w1", "w2", "w3", "w4");
List<String> childOk = Arrays.asList("w1", "w4");
List<String> childKo = Arrays.asList("w1", "xx");
System.out.println(allKnown(parent, childOk));
System.out.println(allKnown(parent, childKo));
打印:
true
false
取出result = true;
-您不想在循環的每一步都將值重置為true
。
還要將wordList.contains
更改為wordList.get
(因為要在特定索引處獲取單詞,而不是檢查單詞是否包含在wordList
),然后移動!
(因為您不能“不”字符串)。
而且,您還可以通過在for循環條件下檢查result
的值(或直接在if語句中直接返回)來進行優化。
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size() && result; index++)
{
if(!words.contains(wordList.get(index)))
{
result = false;
}
}
return result;
}
如果words
確實是一個數組而不是ArrayList
,則它沒有contains
方法,則必須有一個double for循環,或將其轉換為列表:
List<String> parentWords = Arrays.asList(words);
...
if (parentWords.contains(...))
如果沒有,請勿將結果重置為true。 因為這樣,整個函數將始終返回true。
一些提示:
ArrayList
用作方法參數,請始終使用更抽象的List
(您的代碼都不依賴ArrayList
,因此您可以根據需要稍后更改實現)。 List
對象。 words
列表中即可返回false
,因此可以完全做到這一點(如下所示)。
public boolean allKnown(List<String> wordList) {
for (String word : wordList) {
if (!words.contains(word)) {
return false;
}
}
return true;
}
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(String word : wordList)
{
if(!words.contains(word))
{
result = false;
}
}
return result;
}
這是一個簡單的版本:
public boolean allKnown(List<String> wordList) {
List<String> wordListCopy = new ArrayList<String>(wordList);
return !wordListCopy.retainAll(words);
}
PS: retainAll()
從您的wordList
刪除了dictionnary
中未包含的所有元素。 該方法返回true,如果你的wordList
改變為調用的結果(除去非現有元素之后),換句話說,該方法返回false當你所有的wordList
元素存在於你dictionnary
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.