[英]Comparing LinkedList Elements to String in Java
我正在嘗試編寫一個程序,將 LinkedList 中的字符串與單個字符串進行比較。 我正在嘗試檢查 LinkedList 中的字符串是否正好有一些數字:單個字符串中相同字母的int n
。
例如,如果 LinkedList 中的第一個單詞是"word"
,則n = 2
,並且單個字符串是"weed"
。 這些單詞包含 2 個相同的字母。 未遵循此規則的所有其他元素將從 LinkedList 中刪除。 這些單詞的大小也是一樣的。
我已經編寫了下面的代碼,但我擔心這不是實現它的最佳方法,否則 while 循環將無限繼續。
int count = 0;
for (String word : list) {
for (int i = 0; i < str.length(); i++){
while (count != n) {
if (word.contains("" + str.charAt(i))){
count ++;
}
if (count != n) {
list.remove(word);
}
}
}
}
您根本不需要 while 循環來解決這個問題。 這段代碼應該可以工作。
for (String word : list)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (word.contains("" + str.charAt(i)))
{
count ++;
}
}
if (count != n)
{
list.remove(word);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.