java - 如何阻止 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”以外的内容时,如何阻止这是一个无限循环?
解决方案
好吧,我想首先你必须把
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);
推荐阅读
- nativescript - 应用程序启动时 - 如何设置默认时区?(本机脚本)
- python-3.x - 反转熊猫中的多标签二值化器
- xml - XPath 检索模式中选择的节点名称
- php - PHP move_uploaded_file()函数不起作用
- woocommerce - Woocommerce:如何自定义产品类别小部件以显示所选类别?
- python - Why is datetime.now() set to a fixed moment in my module?
- elasticsearch - 安装 Elasticsearch 7 时出错 - 依赖项失败
- python - 如何创建这两个单独的极坐标图?
- css - .green .progress .inner .water { top: 25%; } meaning?
- c# - ASP.NET MVC 站点允许匿名用户但在登录时以登录用户的 AD 身份运行?