You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;
    }
}

关键修复说明

  1. 输入收集修正:将input()改为返回ArrayList<String>的方法,把用户输入直接存入列表并返回给main方法,确保程序能用到用户实际输入的内容。
  2. 元素存在性检查:用pantry.contains(ingredient)判断单个食材是否在pantry中,这是ArrayList自带的元素检查方法,逻辑准确。
  3. 缺失食材统计:创建missingItems列表存储所有缺失的食材,最后拼接成字符串输出,满足作业要求的“输出具体缺失食材”。
  4. 代码可读性优化:修改方法名称(如linearSearch改为checkPantry),让代码逻辑更清晰。

内容的提问来源于stack exchange,提问作者Andrew Yan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:40:30