【发布时间】:2021-08-19 00:13:35
【问题描述】:
我正在创建一个允许根据用户输入打印出购物清单的程序。
我正在尝试添加用户验证,因此当您为产品输入负价时,它会要求用户再次输入一个值,因为您无法添加负价。
虽然控制台确实可以工作,并在您为其提供无效值时要求用户输入另一个值,但它仍会将负值添加到数组中,然后在您付款时将负值添加到总金额中。
有没有办法让我的代码忽略负值而不将其添加到数组列表中?我才刚刚开始,所以会很有帮助。
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;
// asks user for the price of the product
System.out.print("Enter the price for " + product + " : ");
price = sc.nextDouble();
// if user enters negative price it'll be rejected
if (price < 0)
System.out.print("Price cannot be a negative value, please enter price again: ");
sc.nextLine();
// adds product and price to array lists
products.add(product);
prices.add(price);
}
将总数添加到数组列表中:
//method to get the total of the shopping list
public static double getTotalList(ArrayList<Double> prices) {
// variable that stores the total
double total = 0;
// add to the total
for (double i: prices)
total += i;
// return the total
return total;
}
【问题讨论】:
-
您可以将
sc.nextLine()之后的两行移动到其上方的else条件中。总而言之,total += i < 0 ? 0 : i应该可以解决问题。 -
我只是按照建议进行了这几次编辑,但我发现它只是增加了总数:@aksappy 余额应该是 0 美元,因为我只有 3 美元可以花在 3 美元的产品上 产品牛奶 = $ -3.00 总到期: $ -3.00 礼品卡: $ 3.00 礼品卡余额: $ 6.00