"利用多重条件的While循环策略"
"利用多重条件的While循环策略"
我正在寻求如何编写具有多个条件的while
循环的建议。 主要思路是我们有一些要检查的条件,如果它们不符合要求,它们就会被重复。
例如,我们需要输入一些输入(具有两个数字的数字字符串)。 输入必须是数字,不少于3个,并且必须具有相同的数字。 如果任何条件不满足,则通知用户并要求再次输入。 如果输入满足所有要求,则循环停止。 这是最佳情况吗?
我的想法是这样的:
while (true) { if (!(someMethod)) { print("This doesnt meet the condition. Try again!"); continue; } }
continue
可以重复“新”条件的工作,但我不确定最好的退出循环的方法是什么?
admin 更改状态以发布 2023年5月24日
你描述的输入捕获用例似乎适合使用do-while
循环。
- 输入在
do-while
中被重复捕获 - 所有条件可以封装在一个函数中,该函数以捕获的输入作为参数
- 可以使用单个if-else语句,确保循环要么根据条件重复使用
continue
,要么使用break
结束。
do { final String input; //Code that gets input //shouldRepeat should include all conditions if (shouldRepeat(input)) { print("This doesnt meet the condition. Try again!"); continue; } else { print("Success"); break; } } while(true); //Function signature private boolean shouldRepeat(final String input){ //conditions //Condition1 OR Condition2 OR Condition3 }