java - While loop with iteration -
i trying create while loop user has total of 3 tries enter valid number. i'm not understanding how system recognizes 3 invalid attempts have been made before displaying message. classes, variables, , scanner objects made. after 3 attempts, want "no more tries". have program written use user's input quantity if valid. if input 3 invalid attempts.
updated code:
int quantity = 0;
// user's desired amount of lemonade cups system.out.print("hello " + name + ". how many cups of lemonade can you? "); quantity = keyboard.nextint(); // store amount of cups wanted int attempts = 0; int maxattempts = 3; double subtotal = quantity * lemonadecost; double totaltax = subtotal * 0.08; double totalprice = subtotal + totaltax; while (attempts < maxattempts) { if (quantity < 1 || quantity >= 20) { system.out.println("that invalid amount, please try again"); quantity = keyboard.nextint(); } else { system.out.println("subtotal: " + defaultformat.format(subtotal)); system.out.println("tax: " + defaultformat.format(totaltax)); system.out.println("total: " + defaultformat.format(totalprice)); } attempts++; if (attempts >= 3) { system.out.print ("no lemonade you"); break; } // ask user's payment method scanner method = new scanner(system.in); system.out.println("how pay? enter 'm' money, 'c' credit or 'g' gold. "); string payment = method.nextline();
dxdy correct braces required making while() loop function.
once while loop has ended (either quantity between 1 , 20, or attempts > maxattempts), need have if statement following:
if (attempts > maxattempts) { system.out.println("no more tries); return -1; // or else break out of code }
and continue on rest of code working quantity variable.
Comments
Post a Comment