简体   繁体   中英

How to exit a for loop if the if loop inside condition is met

I'm trying to create a method which allows you to choose which index in an array of test scores. It will check what the score is and return a grade for that score. In my getGrade method no matter what the score is it returns "NG".

private double[] scores = new double[3];
private static int[]boundaryVals={80,72,64,60,56,52,48,40,35,30,1,0};
    private static String[]grades={"A1","A2","B1","B2","B3","C1","C2","C3","D1","D2","F","NG"};

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

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.

Because in the end 0 always smaller/equals to i, so even if 80 is less than i, finally i will de "NG" ; Try add the keywords break; after grade = grades[x]; to stop the loop when the condition is true.

break is the keyword you're looking for.

As soon as the break statement is encountered inside a loop, the loop is terminated and it resumes with the next statement.

In your code the loop is never terminated until it gets to the last item in your array, which is 0. And 0 is always smaller than or equal to i. ;)

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