Java中对两个ArrayList<String>实现线性搜索及购物清单程序问题求助
购物清单程序问题修复
你的代码核心问题
- 输入未存入目标列表:你写的
input()方法仅读取用户输入,但这些输入只存在方法的局部变量里,完全没加到main方法的input列表中,导致程序始终用初始的占位字符串(ingredientOne等),根本没用到用户实际输入的内容。 - 列表比较逻辑错误:
pantry == input是判断两个列表对象的内存地址是否相同,不是检查内容匹配,这种写法永远不会返回true,所以无论什么情况都会输出缺失提示。 - 检查方向搞反:应该遍历用户输入的食材,逐个确认是否在pantry中,而不是遍历pantry去对比整个列表。
修复后的完整代码
import java.util.Scanner; import java.util.ArrayList; public class TheList { // 检查食材是否齐全的方法 public static String checkPantry(ArrayList<String> pantry, ArrayList<String> userIngredients) { ArrayList<String> missingItems = new ArrayList<>(); // 遍历用户输入的每一种食材 for (String ingredient : userIngredients) { // 若当前食材不在pantry中,加入缺失列表 if (!pantry.contains(ingredient)) { missingItems.add(ingredient); } } // 根据缺失情况返回对应结果 if (missingItems.isEmpty()) { return "You got everything you need!"; } else { return "You still need: " + String.join(", ", missingItems); } } public static void main(String[] args) { // 初始化pantry清单 ArrayList<String> pantry = new ArrayList<>(); pantry.add("Bread"); pantry.add("Peanut Butter"); pantry.add("Chips"); pantry.add("Jelly"); // 收集用户输入的食材列表 ArrayList<String> userIngredients = collectUserInput(); // 调用检查方法并输出结果 System.out.println(checkPantry(pantry, userIngredients)); } // 收集用户输入,返回食材列表 private static ArrayList<String> collectUserInput() { Scanner scanner = new Scanner(System.in); ArrayList<String> ingredients = new ArrayList<>(); System.out.println("Please enter an ingredient: "); ingredients.add(scanner.nextLine()); System.out.println("Done."); System.out.println("Please enter an ingredient: "); ingredients.add(scanner.nextLine()); System.out.println("Done."); System.out.println("Please enter an ingredient: "); ingredients.add(scanner.nextLine()); System.out.println("Done."); System.out.println("Please enter an ingredient: "); ingredients.add(scanner.nextLine()); System.out.println("Done."); scanner.close(); return ingredients; } }
关键修复说明
- 输入收集修正:将
input()改为返回ArrayList<String>的方法,把用户输入直接存入列表并返回给main方法,确保程序能用到用户实际输入的内容。 - 元素存在性检查:用
pantry.contains(ingredient)判断单个食材是否在pantry中,这是ArrayList自带的元素检查方法,逻辑准确。 - 缺失食材统计:创建
missingItems列表存储所有缺失的食材,最后拼接成字符串输出,满足作业要求的“输出具体缺失食材”。 - 代码可读性优化:修改方法名称(如
linearSearch改为checkPantry),让代码逻辑更清晰。
内容的提问来源于stack exchange,提问作者Andrew Yan
相关产品推荐
相关产品推荐

