如何在开关盒中使用范围

时间:2018-01-26 06:54:52

标签: java switch-statement

我使用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
 *
 */

2 个答案:

答案 0 :(得分:4)

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

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?

答案 1 :(得分:0)

首先,No。Switch是一个错误的选择。与传统的if一起使用。

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