【问题标题】:How to get Java to ignore negative values in an ArrayList?如何让 Java 忽略 ArrayList 中的负值?
【发布时间】: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 &lt; 0 ? 0 : i 应该可以解决问题。
  • 我只是按照建议进行了这几次编辑,但我发现它只是增加了总数:@aksappy 余额应该是 0 美元,因为我只有 3 美元可以花在 3 美元的产品上 产品牛奶 = $ -3.00 总到期: $ -3.00 礼品卡: $ 3.00 礼品卡余额: $ 6.00

标签: java arrays arraylist


【解决方案1】:

如果您需要拒绝负价格,您应该按照@Renis1235 的答案中的建议在循环中读取price,或者您可以使用递归方法读取价格,直到输入有效值:

static double readValidPrice(Scanner sc) {
    double price = sc.nextDouble();
    sc.nextLine(); // skip line break

    if (price < 0) {
        System.out.print("Price cannot be a negative value, please enter price again: ");
        return readValidPrice(sc); // recursive call
    }
    return price;
}

然后从主循环调用这个方法:

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 = readValidPrice(sc); // valid value is guaranteed to be read

    // adds product and price to array lists
    products.add(product);
    prices.add(price);
}

这种方法应该在prices 列表中提供有效值,因此总和应该是正确的。

但是,要强制过滤掉方法 getTotalList 中的负值,您也可以添加价格检查。使用 Java Stream API 的示例如下:

public static double getTotalList(List<Double> prices) {
    return prices.stream()
             .filter(price -> price > 0.0)
             .mapToDouble(Double::doubleValue) // DoubleStream
             .sum();
}

【讨论】:

    【解决方案2】:

    如果用户再次提供负值你应该怎么做你想让他们租用直到有效然后你需要把它放在while循环中 如果(价格

    直到用户间有效值,或者您可以使用 else 语句忽略该值

    或者你在 for each 循环中使用 if 语句来只添加正数

    或使用流,但由于您刚刚开始,那么您可能还没有到达那部分

    【讨论】:

      【解决方案3】:

      这应该可以解决问题:

      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
      
      
          // This is the change, we have a loop which continuously checks if the price is negative, if it is, the user will be asked again
          while (price < 0)
          {
              System.out.print("Price cannot be a negative value, please enter price again: ");
              price = sc.nextDouble();
          }
      
          // adds product and price to array lists
          products.add(product);
          prices.add(price);
      
      }
      

      【讨论】:

        【解决方案4】:

        不是你想忽略消极的输入,而是你只想要积极的输入。

        创建一个处理这个问题的方法:

        double getPrice(Scanner sc, String description) {
            while (true) {
                System.out.print(description + " : ");
                double price = sc.nextDouble();
                sc.nextLine();
        
                if (price >= 0)
                    return price;
                
                System.out.print("Price cannot be a negative value");
            }
        }
        

        然后使用它:

        double price = getPrice(sc, "Enter the price for " + product;
        

        这种方法可以处理任意数量的无效价格,并使主代码更易于阅读。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-21
          • 2011-02-05
          • 2014-11-12
          • 2020-03-04
          • 2020-12-22
          • 2011-10-08
          • 2019-09-24
          • 1970-01-01
          相关资源
          最近更新 更多