我有以下代码会导致无限循环:
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”以外的内容时,如何阻止它成为无限循环?
答案 0 :(得分:1)
好吧,我想首先您必须放上
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);
答案 1 :(得分:0)
要阻止循环无限循环,必须避免该条件保持为真,否则它不会停止。如果要在根据情况做出响应后停止循环,请中断循环。
对于您的情况,您可以按照以下步骤进行操作(请记住,如果第一个值未经验证,则必须选择另一个值,这就是为什么invoice=choice.nextInt()
必须包含在循环的顶部):
do
{
invoice = choice.nextInt();
if(invoice == 1)
{
System.out.println("one");
break;
//quit the loop after the operation
}
else if (invoice == 2)
{//we add else if because invoice might be either 1 or 2 or another value and not two values at same time.
System.out.println("two");
//quit the loop after the operation
}
else
{
System.out.println("Press '1' to Pay and '2' to Add");
//don't break here because you are just leaving a message to let the user know invoice must be either one or two and if not display the message
}
}while(invoice >= 3 || invoice <=0);
答案 2 :(得分:0)
确定输入<1>或'2'以外的内容时是否要停止循环?
通常的做法是,当用户输入有效选择1
或2
时,停止这种循环,并给出诸如0
之类的另一种退出选项。
因此,只要用户未输入1
或2
,循环就不会结束:
Scanner choice = new Scanner(System.in);
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 or '2' to Add, '0' to Exit");
invoice = choice.nextInt();
if (invoice == 0) {
System.out.println("Exiting...");
break;
} else if(invoice == 1) {
System.out.println("one");
break;
} else if (invoice == 2) {
System.out.println("two");
break;
}
} while(invoice < 0 || invoice > 2);