how do i exit a loop if the if loop inside condition is met?

Just change the loop exit condition to terminate when a grade has been assigned.

public String getGrade(int i) {
    String grade = "";
    for(int x=0; x<boundaryVals.length && !grade.equals(""); x++) {
        if (boundaryVals[x] <= i) {
            grade = grades[x];               
        }
    }
    return grade;
}

This is better-structured since it has the loop termination condition in one place, rather than spreading it out by use of “break”.

As usual, this is not a hard and fast rule. For more complicated cases, “break” is clearer. It’s a matter of taste.

The ‘return’ from mid-loop, as suggested in comments, is not a bad solution in this particular case either. But I think it’s worth pointing out that loop conditions are not limited to simple counting from 0 to N.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top