Java使用枚举来消除if else(转载)
Java代码里经常出现多个if else会大大降低效率,我们可以使用枚举的方式来代替if else,示例代码如下:
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)); } }
看完打开支付宝扫一扫领个红包吧!