简体   繁体   English

同时执行循环无法持续工作

[英]do-while loop is not constantly working

does anybody see wrong code here ?? 有人在这里看到错误的代码吗? i'd like to see do-while is working constantly as long as condition is not satisfied but it is certainly not. 我希望看到只要条件不满足,“做一会儿”就一直在工作,但肯定不是。 please tell me which part of code ruins my expected result? 请告诉我代码的哪一部分破坏了我的预期结果?

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() does not consume any characters following the integer value, so the CR LF after it is still in the buffer and is read by the nextLine() call, meaning that keepShopping is always a blank string (or whatever was typed after the quantity value on the same line). nextInt()在整数值之后消耗任何字符,因此CR LF仍在缓冲区中,并由nextLine()调用读取,这意味着keepShopping始终为空字符串(或在数量后键入的任何内容)值)。

Your code is also calling nextDouble() and nextInt() without first calling the corresponding hasNextDouble() and hasNextInt() methods, so if you type something wrong, the program will crash and burn. 您的代码还调用了nextDouble()nextInt()而没有先调用相应的hasNextDouble()hasNextInt()方法,因此,如果您键入错误的内容,程序将崩溃并刻录。 Very common flaw in the use of Scanner . 使用Scanner非常常见的缺陷。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM