【问题标题】:How to exit a Double ArrayList's While Loop with a negative int value check?如何通过负 int 值检查退出 Double ArrayList 的 While 循环?
【发布时间】:2017-09-12 12:25:28
【问题描述】:

这是一个购物清单程序。用户为她列表中的每个项目输入一个值,例如 $2.00。但是如果她想退出这部分程序,她输入“-1”

我理解这个 Double ArrayList 和 int “-1” 是“无法比较的类型”,正如编译器错误消息所显示的那样。

对有关 Double ArrayList 的 int "-1" 退出代码有何建议?

谢谢你。

这是我的代码:

 ArrayList<Double> priceInputAnswer = new ArrayList<Double>()                

                {
                    System.out.print("Please enter an item price, or -1 to exit: $");
                    Scanner numberReader = new Scanner (System.in); 
                    while (numberReader.hasNextDouble())
                        {
                        priceInputAnswer.add(numberReader.nextDouble());

                        }

                                while (priceInputAnswer != -1) 

}

【问题讨论】:

  • priceInputAnswer 不是int;从逻辑上讲,您不会将列表与不是列表的内容进行比较。这是将苹果与橙子进行比较的众所周知的案例。
  • 非常感谢您的快速帮助。

标签: java arraylist int double


【解决方案1】:

您的实际代码似乎无法编译。

无论如何,您可以分两步完成。
1) 将来自扫描仪的值存储在 priceInput 变量中
2)在while语句中使用:while (priceInput != -1)

do/while 表单不一定是满足您需求的最佳表单。
你应该写这样的东西:

double priceInput = -1;
do {
    priceInput = numberReader.nextDouble();
    if (priceInput != -1) {
        priceInputAnswer.add(priceInput);
    }
} while (priceInput != -1);

一个while 在看起来更自然之前检索了一个输入,因为它避免了循环中的if 语句:

double priceInput = numberReader.nextDouble();
while (priceInput != -1) {
    priceInputAnswer.add(priceInput);
    priceInput = numberReader.nextDouble();
}

【讨论】:

  • 非常感谢您的快速和最详细的帮助。尤其是 Java 代码编写最佳实践的细节。您的建议当然是有效的,并帮助我克服了编译器的僵局。正如我的教授所建议的那样,还使我能够更好地学习如何简化代码。
猜你喜欢
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多