我正在尝试创建一个 while 循环,其中用户总共尝试输入有效数字三次。我不明白系统如何识别在显示消息之前已经进行了 3 次无效尝试。 创建类、变量和扫描仪对象。经过三次尝试后,我想说“不再尝试”。我已经编写了程序,以使用用户输入的数量(如果有效)。这仅适用于他们输入三个无效尝试的情况。
Updated code:
整数数量 = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get 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 is an 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 for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
最佳答案
dxdy关于创建 while() 循环函数所需的大括号,正确的是。
一旦 while 循环结束(数量在 1 到 20 之间,或者尝试次数 > maxAttempts),您只需要一个如下的 if 语句:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
然后继续使用数量变量的其余代码。
关于java - 带迭代的 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32856806/