简体   繁体   English

如果满足 if 循环内部条件,如何退出 for 循环

[英]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".在我的 getGrade 方法中,无论分数是多少,它都会返回“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.对于更复杂的情况,“break”更清晰。 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.但我认为值得指出的是,循环条件不限于从 0 到 N 的简单计数。

Because in the end 0 always smaller/equals to i, so even if 80 is less than i, finally i will de "NG" ;因为最终 0 总是小于/等于 i,所以即使 80 小于 i,最后 i 也会 de "NG" Try add the keywords break;尝试添加关键字break; after grade = grades[x]; grade = grades[x];grade = grades[x]; to stop the loop when the condition is true.当条件为真时停止循环。

break is the keyword you're looking for. break是您要查找的关键字。

As soon as the break statement is encountered inside a loop, the loop is terminated and it resumes with the next statement.一旦在循环中遇到 break 语句,循环就会终止并继续执行下一个语句。

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.在您的代码中,循环永远不会终止,直到它到达数组中的最后一项,即 0。并且 0 始终小于或等于 i。 ;) ;)

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

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