Home > other >  Using do while loops
Using do while loops

Time:01-04

The loops still continue even though I type "0" for quantity. What is wrong here and how can I fix this to stop when I type "0" for quantity?

Scanner myinput = new Scanner(System.in);
        int total ;
        int quantity = 0;
        String name = null;
        double price;

        
        do
        {
            System.out.println("Please type the quantity of your item(s) (ex : If you have 2 shirts, please type 2)");
            quantity = myinput.nextInt();

            System.out.println("Please type the name of your item(s)");
            name = myinput.next();

            System.out.println("Please type the price of your item(s)");
            price = myinput.nextDouble();
        
        }while (quantity == 0);

CodePudding user response:

Your quantity is 0. Your While-Loop asks "Is this Value 0? If it is, i will do this again." Which is exactly what happens.

In that case you simply have to change while (quantity == 0) to while (quantity != 0), which basically asks the opposite.

"Is this Value not 0? If it is not 0, then i do this again. If it is 0, then i will stop doing this."

CodePudding user response:

As stated here, you need to change the 'do while' condition. You can either check for quantity != 0 or quantity > 0. Hence you will have

do
{

//your code here

}while (quantity > 0)

This way it only enters the loop once, the first time, when it will ask for quantity, name and price, and THEN it will check if the quantity is different/bigger than 0. If you want to check the quantity before name and price, you should do separate do while loops for each check.

  •  Tags:  
  • Related