1

I use the switch case to get a large range:

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
 *
 */
aUserHimself
  • 1,589
  • 2
  • 17
  • 26
Kaif
  • 29
  • 1
  • 6
  • 2
    you don't. switch is for specific cases. sure, you can use the waterfall way, but then you would have to write a line for each value in the range, and it wouldn't be dynamically. for ranges, use if statements instead – Stultuske Jan 26 '18 at 06:55
  • 3 seconds of using Google on `java switch case range` gave me the first hit: https://stackoverflow.com/questions/10873590/in-java-using-switch-statement-with-a-range-of-value-in-each-case – derHugo Jan 26 '18 at 07:33
  • As other mentioned, probably only possibility is to avoid using `break` statements of the cases in the switch statement, but it is against the conventions and if you will be using some code quality analysis tool, this solution will be marked as code smell, but in general it should works – xxxvodnikxxx Jan 26 '18 at 09:25

2 Answers2

4

You can't do it for large range. But you can try like this (even though it is not a good practice):

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

I suggest you to use if else statements.

if you want more details see these:

java - switch statement with range of int

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

DerBobby
  • 356
  • 3
  • 9
dilusha_dasanayaka
  • 1,401
  • 2
  • 17
  • 30
0

To start with, No. Switch is a wrong choice here. Go with traditional if's.

if(x>0 && x <100){
 // do something
}..
..
..
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307