gpt4 book ai didi

java - do-while 循环不是一直在工作

转载 作者:行者123 更新时间:2023-12-02 03:58:16 27 4
gpt4 key购买 nike

有人在这里看到错误的代码吗?我希望看到只要条件不满足, do-while 就会不断工作,但它肯定不是。请告诉我哪部分代码破坏了我的预期结果?

public static void main (String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Item> cart = new ArrayList<Item>();
Item item;
String itemName;
double itemPrice;
int quantity;
String keepShopping;
double total = 0.0;
DecimalFormat m = new DecimalFormat("######,##");
do {
System.out.print ("Enter the name of the item: ");
itemName = scan.nextLine();
System.out.print ("Enter the unit price: ");
itemPrice = scan.nextDouble();
System.out.print ("Enter the quantity: ");
quantity = scan.nextInt();

item = new Item(itemName,itemPrice,quantity);
cart.add(item);
total +=itemPrice*quantity;

System.out.println ("Continue shopping (y/n)? ");
keepShopping = scan.nextLine();

} while (keepShopping.equals("y"));

for (int i = 0; i < cart.size(); i++) {
System.out.println(cart.get(i).toString());
System.out.println("Total price: " + m.format(total));
}
scan.close();
}

最佳答案

nextInt() 不会消耗整数值后面的任何字符,因此它后面的 CR LF 仍然在缓冲区中并且是由 nextLine() 调用读取,这意味着 keepShopping 始终是空白字符串(或在同一行的数量值之后键入的任何内容)。

您的代码还调用了 nextDouble()nextInt(),而没有先调用相应的 hasNextDouble()hasNextInt( ) 方法,因此如果输入错误,程序将崩溃并烧毁。使用 Scanner 时非常常见的缺陷。

关于java - do-while 循环不是一直在工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35211581/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com