gpt4 book ai didi

java - 如何阻止 do...while 循环无限

转载 作者:行者123 更新时间:2023-11-30 05:53:04 27 4
gpt4 key购买 nike

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

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”以外的内容时,如何阻止无限循环?

最佳答案

好吧,我想首先你必须把

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);

关于java - 如何阻止 do...while 循环无限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53606947/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com