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

如何实现Java ArrayList自动过滤用户录入的负价格数值?

问题分析

你的代码核心问题是价格校验逻辑不完整:仅做了负价格的提示,没有阻止无效值写入列表,也没有要求用户重新输入合法值,所以无论输入的价格是否为负,都会被直接加入ArrayList。

修复后的代码

以下是调整后的While循环代码:

// while loop until user enters the product
while (true) {

    // asks user for product input
    System.out.print("Please enter product name or enter 'x' to finish: ");
    product = sc.nextLine();
    // terminates the loop if the user enters x
    if (product.equalsIgnoreCase("x"))
        break;

    // 价格输入循环,直到拿到合法值为止
    double price = -1;
    while (price < 0) {
        // asks user for the price of the product
        System.out.print("Enter the price for " + product + " : ");
        price = sc.nextDouble();
        sc.nextLine(); // 处理nextDouble残留的换行符
        if (price < 0) {
            System.out.println("Price cannot be a negative value, please enter price again.");
        }
    }

    // 只有拿到合法价格后才添加到列表
    products.add(product);
    prices.add(price);
}

你的总金额计算方法本身没有问题,无需修改,调整后不会再有负价格进入列表,总金额计算也会正常。

修改说明
  • 新增了嵌套的价格校验循环:只要用户输入的价格小于0,就会反复提示重新输入,直到获取到合法的非负价格
  • 将列表添加操作移到了价格校验通过之后,确保只有有效的商品和价格才会被写入ArrayList
  • 统一了Scanner换行符的处理位置,避免读取数字后残留的换行符被后续nextLine读取,导致商品名称输入异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:18:01