首页 > 解决方案 > 如何阻止 do...while 循环无限

问题描述

我有以下导致无限循环的代码:

System.out.println("Adjust Invoices");
System.out.println("Would like to Pay an invoice or Add an invoice to your account?");
System.out.println("Press '1' to Pay and '2' to Add");
int invoice = choice.nextInt();
do
{
    if (invoice == 1)
    {
        System.out.println("one");
    }
    if (invoice == 2)
    {
        System.out.println("two");
    }
    else
    {
        System.out.println("Press '1' to Pay and '2' to Add");
    }
} while (invoice >= 3 || invoice <=0);

当我输入“1”或“2”以外的内容时,如何阻止这是一个无限循环?

标签: javaloops

解决方案


好吧,我想首先你必须把

int invoice = choice.nextInt();

在你的循环中避免这种情况。否则使用循环是没有意义的。如果输入错误,您想循环,对吗?好吧,这只有在您允许用户更正他们的输入时才有意义。

然后,我会在出现有效输入时立即停止,并将提示打印放在末尾,而不使用“else”。此外,如果您在这些点上休息,您可以消除您的状况。这将是多余的。您的提示也是多余的,所以只需在输入之前输入。所以,你最终得到的是:

System.out.println("Adjust Invoices");
System.out.println("Would like to Pay an invoice or Add an invoice to your account?");

int invoice;
do
{
    System.out.println("Press '1' to Pay and '2' to Add");
    invoice = choice.nextInt();
    if (invoice == 1)
    {
        System.out.println("one");
        break;
    }
    if (invoice == 2)
    {
        System.out.println("two");
        break;
    }
} while (true);

推荐阅读