java - 带迭代的 While 循环

标签 java loops while-loop

我正在尝试创建一个 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/

相关文章:

c# - 使用循环来确定数字是否有效 C#

java - 输入正确的值后程序不会退出循环

java - While 循环建议?

java - 通过 Eclipse 以管理员身份运行 ant

java - 使用 Android 共享 Intent 在 Facebook 中共享文本

java - 将 `TransformingRandomAccessList<T>` 转换为 `List<T>`

java - 如何在Java中的所有类中共享使用哪个Locale?

java - For 循环和数字的整除性

java - 将 While 循环合并到程序中

C++无限循环