"利用多重条件的While循环策略"

28 浏览
0 Comments

"利用多重条件的While循环策略"

我正在寻求如何编写具有多个条件的while循环的建议。 主要思路是我们有一些要检查的条件,如果它们不符合要求,它们就会被重复。

例如,我们需要输入一些输入(具有两个数字的数字字符串)。 输入必须是数字,不少于3个,并且必须具有相同的数字。 如果任何条件不满足,则通知用户并要求再次输入。 如果输入满足所有要求,则循环停止。 这是最佳情况吗?

我的想法是这样的:

while (true) {
    if (!(someMethod)) {
        print("This doesnt meet the condition. Try again!");
        continue;
    }
}

continue可以重复“新”条件的工作,但我不确定最好的退出循环的方法是什么?

admin 更改状态以发布 2023年5月24日
0
0 Comments

循环之前可以读取初始输入并在循环条件中使用逻辑 OR 条件的反转。

//read initial input
while(!condition1() || !condition2() || !condition3()) {
  //inform input is not valid
  //read next input
}

只要至少有一个条件未满足 - 被评估为 false,循环就会继续。当所有条件都满足 - 全部都是 true 时,循环结束。

0
0 Comments

你描述的输入捕获用例似乎适合使用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
}

0