如何实现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
相关产品推荐
相关产品推荐

