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

标签 java

有人在这里看到错误的代码吗?我希望看到只要条件不满足, 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/

相关文章:

java - 合并排序未给出正确的输出

java - 当计数器从 1 开始时,递归方法出现堆栈溢出

java - CardView onClick点击测试?

java - Midiplayer 在 16 个音符后停止播放声音

java - 连接两个具有交替值的数组

java - JUnit 测试 : How to check for errors with a try-catch block

java - 将 Retrofit 与 Flex Mobile 应用程序结合使用

java - 代号一应用程序生命周期

java - 如何在 spring bean 上强制/验证 spring 范围注释

java - 使用波形文件进行指纹匹配