【问题标题】:Switch statement with boolean expressions in case labels [duplicate]案例标签中带有布尔表达式的switch语句[重复]
【发布时间】:2018-02-21 13:37:16
【问题描述】:

我正在学习 Java,但在使用带有表达式的 switch-case 语句时遇到了问题。有人能帮助我吗? 我无法理解我在哪里犯了错误。

package SecondSet_StartingArray;

import java.util.Scanner;

public class Testing 
{
    public static void main(String[] args) {

    System.out.println("Enter a Number between 1 & 100");
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    switch (i)
    {
        case (i>90):    System.out.println("Rating 5");break;
        case (i<=90):   System.out.println("Rating 4");break;
        case (i<=60):   System.out.println("Rating 3");break;
        case(i<=30):    System.out.println("Rating 2");break;
        case(i>29):     System.out.println("Rating 1");break;
    }
}

}

【问题讨论】:

  • switch case 需要一个具体的值,而不是像i&lt;=90 这样的条件。如果您有条件,请创建一个 `if else if else if ... 构造。
  • 除了使用 case 100:case 99 : .... : case 91 .. 之外还有什么简单的方法吗
  • 仅根据当前代码的逻辑,您可以得到评分:int rating = i/30 + 1

标签: java switch-statement


【解决方案1】:

您不能将 switch-case 与 case (i&lt;=90) 等布尔表达式一起使用。您的案例必须是要评估的常量表达式。

case 90: whatever; break;
case 120: whatever; break;
case SOME_CONSTANT: whatever; break;

根据您的需要,您需要使用 if-else-if 语句。

【讨论】:

    【解决方案2】:

    您想要实现的是if-else-statementSwitch-Statements 在您尝试评估常量值时使用。

    【讨论】:

    • 非常感谢,我已经尝试过 if else 语句,我只是想弄清楚 case 语句中是否有选项,因为它更简单。
    【解决方案3】:

    正如您在 Java 语言规范 here 中看到的那样:

    以下所有条件都必须为真,否则会发生编译时错误:

    1. 与 switch 语句关联的每个 case 常量表达式都必须可分配(第 5.2 节)到 switch 表达式的类型。
    2. 与 switch 语句关联的任何两个 case 常量表达式都不能具有相同的值。
    3. 没有任何开关标签为空。
    4. 最多可以有一个默认标签与同一个 switch 语句相关联。

    在您的代码中,第一点不满足。您可能希望在此处使用if-else-if 语句而不是switch 来正确检查存储在i 中的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-22
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      相关资源
      最近更新 更多