Java使用枚舉來消除if else(轉載)

 

 

Java代碼裏常常出現多個if else會大大下降效率,咱們可使用枚舉的方式來代替if else,示例代碼以下:this

public enum Grade {

    A_10_90(90, 100, "A"), B_90_80(80, 90, "B"), C_80_60(60, 80, "C"), D_60_0(0, 60, "D"), OTHER(-1, -1, "E");

    private int start;
    private int end;
    private String grade;

    Grade(int start, int end, String grade) {
        this.setStart(start);
        this.setEnd(end);
        this.setGrade(grade);
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getEnd() {
        return end;
    }

    public void setEnd(int end) {
        this.end = end;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public static String getGrade(int score) {
        for (Grade grade : values()) {
            if (grade.getStart() <= score && score < grade.getEnd()) {
                return grade.getGrade();
            }
        }
        return OTHER.getGrade();
    }

}
public class GradeTest {
    
    @Test
    public void test() {
        System.out.println(Grade.getGrade(78));
    }
    
}
相關文章
相關標籤/搜索