有人看到错误的代码吗?我希望看到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();
}
答案 0 :(得分:2)
nextInt()
不消耗整数值后面的任何字符,因此CR LF
后面的nextLine()
仍在缓冲区中并被keepShopping
调用读取,意味着nextDouble()
始终是一个空白字符串(或在同一行上的数量值之后键入的任何内容)。
您的代码也在调用nextInt()
和hasNextDouble()
而没有先调用相应的hasNextInt()
和Scanner
方法,因此如果输入错误,程序将崩溃并刻录。使用{{1}}时非常常见的缺陷。