user307610
user307610

Reputation: 11

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();
}

Upvotes: 0

Views: 72

Answers (1)

Andreas
Andreas

Reputation: 159086

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).

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. Very common flaw in the use of Scanner.

Upvotes: 2

Related Questions