Tha*_*tan 2 java enums case switch-statement
我正在尝试使用枚举和switch语句为测试实现一个评分系统,但是使用当前代码我得到的结果总是"null".我看不出哪里出了问题,有人可以帮忙吗?
public enum Grade {
A, B, C, D, E, U;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the students mark:");
int points = scan.nextInt();
if (points < 0 || points > 200) {
System.out.println("Error! points must be between 0 & 200");
} else {
System.out.println(findGrade(points));
}
}
public static Grade findGrade(int points) {
switch (points) {
case 1:
if (points>= 0 && points <= 59) {
return Grade.valueOf("U");
}
case 2:
if (points >= 60 && points <= 89) {
return Grade.valueOf("E");
}
case 3:
if (points >= 90 && points <= 119) {
return Grade.valueOf("D");
}
case 4:
if (points >= 110 && points <= 139) {
return Grade.valueOf("C");
}
case 5:
if (points >= 140 && points <= 169) {
return Grade.valueOf("B");
}
case 6:
if (points >= 170 && points <= 200) {
return Grade.valueOf("A");
}
default:
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我们来看看吧
switch (points) {
case 1:
if (points >= 0 && points <= 59) {
return Grade.valueOf("U");
}
Run Code Online (Sandbox Code Playgroud)
你基本上说的是:
if (points == 1) {
if (points >= 0 && points <= 59) {
return Grade.valueOf("U");
}
}
Run Code Online (Sandbox Code Playgroud)
这是胡说八道.在这种情况下,我认为你根本不需要切换.只需使用:
if (points < 0) {
return null;
}
if (points <= 59) {
return Grade.valueOf("U");
}
if (points <= 89) {
return Grade.valueOf("E");
}
if (points <= 119)
return Grade.valueOf("D");
}
...
return null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1092 次 |
| 最近记录: |