【发布时间】:2017-12-02 04:32:31
【问题描述】:
我正在尝试设计一个购物车,它可以读取美元金额,然后将这些值打印回来。但是,我的 while 循环不会终止,并且我的数组列表存储了错误的值。
/**
* This method is the shopping cart
*/
public static void shoppingCart()
{
// create scanner objects
Scanner textReader = new Scanner(System.in);
Scanner numberReader = new Scanner(System.in);
// declare variables
int counter = 0;
// create arraylist object
ArrayList<Double> cartItems = new ArrayList<Double>();
// create decimal format object
DecimalFormat dollarformatter = new DecimalFormat("$#0.00");
// print out the first prompt
System.out.print("Would you like to input item/s - y/n: ");
String response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
// create while loop for positive response
while ((response.equalsIgnoreCase("y")))
{
System.out.print("Please enter an item price, or -1 to exit: $");
double values = numberReader.nextDouble();
cartItems.add(values);
if ((values > (-1)))
{
System.out.print("Please enter another item price, or -1 to exit: $");
values = numberReader.nextDouble();
cartItems.add(values);
}
else if ((values <= (-1)))
{
System.out.println();
System.out.println("********** Here are your items **********");
System.out.println();
for (counter = 0; counter < cartItems.size(); counter++)
{
System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter));
}
}
}
System.out.println();
System.out.println("********** Thank you for using the shopping cart **********");
}
结果应如下所示:
但这是我的输出:
- while 循环不会终止并返回第一个提示:“请输入商品价格,或 -1 退出:”
- 程序不断将“-1”计数为数组列表的一部分。 “-1”值应该充当“否”并终止向 arrayList 添加更多元素,但在我的代码中,它被吸收到 arrayList 中。我尝试将“-1”转换为字符串以让程序“忽略”它,但它不起作用。
- 程序列出最后一项后(在我的输出中是#3),它应该询问用户是否要删除一项。我还没有做到这一点,因为我对为什么我的 while 循环拒绝终止以及为什么“-1”一直被包含在我的数组列表中感到很困惑。非常感谢您对此提供的任何帮助,因为我已经考虑了一天,但没有运气。
更新代码;循环终止问题似乎已解决,但“-1”并未触发退出,它仍被添加到 arrayList。
while ((response.equalsIgnoreCase("y"))) {
System.out.print("Please enter an item price, or -1 to exit: $");
double values = numberReader.nextDouble();
cartItems.add(values);
while ((values != (-1))) {
System.out.print("Please enter another item price, or -1 to exit: $");
values = numberReader.nextDouble();
cartItems.add(values);
}
System.out.println();
System.out.println("********** Here are your items **********");
System.out.println();
for (counter = 0; counter < cartItems.size(); counter++) {
System.out.println("Item #" + (counter + 1) + ": " + cartItems.get(counter));
}
break;
}
【问题讨论】:
-
您的 else if 语句仍在 while 循环内,因此将再次打印提示。也许你应该考虑加入一个 break 语句?此外,您在 if 和 else 语句之前将值添加到购物车,因此它仍会添加 -1。
-
您能解释一下为什么它不会将“-1”读作“退出”吗?即使我输入“-1”,代码也会继续运行。
-
当条件为真时,while 循环会不断重复。 if else 语句被输入,但它回到了 while 循环的顶部。
标签: java if-statement arraylist while-loop