简体   繁体   English

是否可以退出if语句并返回内部for循环?

[英]Is it possible to exit out of an if-statement and return to an inner for-loop?

Is there a command to exit an if-statement inside of a inner for-loop and have it only go through that inner for-loop? 是否有命令在内部for循环内退出if语句,并使其仅通过该内部for循环?

ex: 例如:

for (int i = 0; i < blah.length; i++) {
    blh = scan.nextDouble();            
    blah[i] = blh;

    if(scores[i] < MIN || scores[i] > MAX_SCORE) {
        errFlag = true;
        System.out.println("ERROR: Enter numbers in the range of " +
            MIN + "-" + MAX_SCORE + "!");
        System.out.print("ERROR: Enter all " + numStudents + " scores again: ");
        errFlag = false;
    }                       
}

You may use label block 您可以使用标签块

FOUND: {
    for(Type mt: TypeList)
       if(condtion(mt))
            break FOUND;
    // not found code here
}

As per Java Language Specification 14.7 根据Java语言规范14.7

A labeled statement is executed by executing the immediately contained Statement. 带标签的语句通过执行立即包含的语句来执行。 If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. 如果该语句用标识符标识,并且包含的​​语句由于与同一标识符的中断而突然完成,则带标签的语句将正常完成。 In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason 在其他所有语句的突然完成情况下,带标签的语句由于相同的原因而突然完成

If you want it to exit the if statement, but stay in the for loop, you can you use the continue statement. 如果希望它退出if语句,但留在for循环中,则可以使用continue语句。 It is like a break statement, but it just skips the remaining part of the loop, and continues at the beginning the loop. 它就像一个break语句,但是它只是跳过了循环的其余部分,并在循环的开始处继续。

Other option: 其他选择:

if you want to skip the further code in the if block but do not intend to break the loop, you can extract that code in a new method and return in between (based on desired condition), that way you can achieve your purpose (if I understand the question correctly) 如果您想跳过if块中的其他代码,但又不想破坏循环,则可以使用新方法提取该代码,然后在两者之间返回(根据所需条件),从而可以达到目的(如果我正确理解了这个问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM