[英]why is everything getting removed from my arraylist?
我試圖回答這個問題:
對 findIngredients 方法進行編程。 該方法接受一個名為 foodInStock 的字符串和一個名為成分的字符串數組列表。 該方法應返回在 foodInStock 中未找到的成分的 ArrayList。
例如,如果:
foodInStock = “tomatopotatocornturkeycarrotstuffing”
ingredients = {“potato”, “corn”, “salt”, “chicken”, “turkey”}
返回{“鹽”,“雞”}
我嘗試編寫一些代碼,但由於某種原因,當我在我的程序中使用上面的示例時,所有內容都被刪除了。 我的程序哪里出錯了?
這是我的代碼:
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients){
ArrayList<String> ingredientsNotFound = new ArrayList<String>();
int i = 0;
for (; i < ingredients.size(); i++) {
for (int x = 0; x < foodInStock.length()-(ingredients.get(i).length())+1; x++) {
if (ingredients.get(i) == foodInStock.substring(x, (x + ingredients.get(i).length()))) {
ingredients.remove(i);
i = 0;
break;
}
}
}
ingredients = ingredientsNotFound;
return ingredientsNotFound;
}
我認為這里有兩個主要內容。
首先,構建最終結果的方式。 您當前正在從原始輸入中刪除項目; 更好的策略是將項目添加到新列表中(部分原因是考慮起來更簡單,部分原因是您通常不想在迭代列表時修改它)。
您也可能不小心在最后用一個空列表覆蓋了您的列表。
二、判斷該成分是否在字符串輸入中的方法。 您可以使用indexOf()
方法查看字符串是否包含當前項,而不是遍歷整個字符串並檢查子字符串。
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients) {
ArrayList<String> results = new ArrayList<>();
for (String ingredient : ingredients) {
if (foodInStock.indexOf(ingredient) == -1) {
results.add(ingredient);
}
}
return results;
}
在這里,我們為結果初始化一個新列表。 然后我們遍歷輸入列表中的每個單獨成分,並詢問該成分是否存在於字符串輸入中。 如果不是( indexOf()
返回-1
),我們將其添加到結果列表中。 最后,結果包含未找到的所有成分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.