【问题标题】:how to use a range in switch case [duplicate]如何在开关盒中使用范围[重复]
【发布时间】:2018-01-26 06:54:51
【问题描述】:

我使用switch case 来获得大范围:

class New {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Your Marks:");
        int x = scan.nextInt();
        switch(x){
        case [100-0]:
            /*
            * getting a large range
            *
            */ 
            System.out.println("good");
            break;
        /**
        *rang between 100-0 or some large range
        *other ways to get the range in switch case
        */
        default:
            System.out.println("Invalid input");
            break;
        }
    }
}
//**
 *need to switch between large range in switch case is it posible on switch 
 *case
 *
 */

【问题讨论】:

  • 你没有。 switch 是针对特定情况的。当然,您可以使用瀑布方式,但是您必须为范围内的每个值写一行,而且它不会是动态的。对于范围,请改用 if 语句
  • java switch case range 上使用 Google 的 3 秒给了我第一击:stackoverflow.com/questions/10873590/…
  • 正如其他提到的,可能唯一的可能是避免在 switch 语句中使用 break 的 case 语句,但这违反了约定,如果您将使用一些代码质量分析工具,这个解决方案将被标记为代码异味,但通常它应该可以工作

标签: java switch-statement


【解决方案1】:

你不能在大范围内这样做。 但是你可以这样尝试(即使这不是一个好习惯):

switch(x){
    case 1:
    case 2:
    case 3:
    case 4:
    case 5: 
  System.Out.Println("cases are between 1 to 5");
break;  
}

我建议你使用 if else 语句。

如果您想了解更多详细信息,请参阅以下内容:

java - switch statement with range of int

In Java,Using switch statement with a range of value in each case?

【讨论】:

    【解决方案2】:

    首先,不。Switch 在这里是一个错误的选择。使用传统的if's。

    if(x>0 && x <100){
     // do something
    }..
    ..
    ..
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-10
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多