gpt4 book ai didi

java - switch 语句返回 null

转载 作者:行者123 更新时间:2023-12-02 02:49:35 28 4
gpt4 key购买 nike

我正在尝试使用枚举和 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;
}
}

}

最佳答案

我们来看看

switch (points) {
case 1:
if (points >= 0 && points <= 59) {
return Grade.valueOf("U");
}

你的意思基本上是:

if (points == 1) {
if (points >= 0 && points <= 59) {
return Grade.valueOf("U");
}
}

这是废话。我认为在这种情况下你根本不需要切换。只需使用:

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;

关于java - switch 语句返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20201153/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com