java - switch 语句返回 null

标签 java enums switch-statement case

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

相关文章:

mysql - 统计每个部门的所有连接用户

java - 这个java程序是如何工作的?

php - Javascript switch 不接受传递的变量

Java - 为尚未实例化的类编写代码?

java - 如何获取java 1.4中使用的原生C语言库的源码?

c++ - 如何将枚举传递给模板参数

c - 开关盒基本型

ios - 如何在快速单击按钮时更改开关状态

java - While-Loop 完成问题和最终值计算

java - 创建 ListView 时出现运行时错误