简体   繁体   中英

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?

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

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. It is like a break statement, but it just skips the remaining part of the loop, and continues at the beginning the loop.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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