简体   繁体   中英

scanner input, double do while loop

I need some help with using a do while loop for an input with scanner. When the incorrect value is entered, I want an error message to display and then be forced to re enter a value. At the moment it shows the error message but continues to proceed onwards.

double price;
do { 
  System.out.print("What is the price of " + name + "? ");
  price = (double) input.nextDouble();
  if (price <= 0) {
    System.out.println("Error - burgers must be over $0");
  }
} while (price < 0);
input.nextLine(); // flush input line

Just chage the do-while condition form

while (price < 0);

to

 while (price <= 0);

as your current while condition is only chekcing for values less than 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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