2016-02-04 69 views
0

有没有人看到错误的代码?只要条件不满意,我希望看到do-while一直在不断工作,但肯定不是。请告诉我哪部分代码会毁掉我的预期结果?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

请把它降低到[mcve]并告诉我们你正在使用什么输入。 –

+0

提示:阅读完'keepShopping'后打印出来。我怀疑这个价值不是你期望的。 –

+0

@ user307610我猜你有多余的空格或导致值不等于“y”的东西。尝试在keepShopping上调用修剪。 – Phil

回答

2

nextInt()消耗后的整数值的任何字符,所以CR LF后,它仍然是在缓冲区中,由nextLine()通话读取,这意味着keepShopping始终是一个空字符串(或任何为在同一行上的数量值之后键入)。

您的代码还呼吁nextDouble()nextInt()没有首先调用相应的hasNextDouble()hasNextInt()方法,所以如果你键入一些错误,程序会和好如初。在使用Scanner时非常常见的缺陷。