0

I need to access the same function for all the cases so I implemented the multiple cases in the if condition. as IDE Throws an error for this, it is obvious that this is the wrong implementation. But is there something which can be an alternative to such logic.

java

 void movie() {
                int m;
                System.out.println("Choose the movie :");
                System.out.println("1.BAHUBALI\n2.SHIVAAY\n3.DANGAL\n4.AIRLIFT");
                m =sc.nextInt();
          switch(m){
                if(case 1: || case 2: || case 3: || case 4:) {
                     Payment();
                }

                else {
                    System.out.println("Choosen an Invlid option");
                }
            }
        }
Aniket Jadhav
  • 508
  • 4
  • 16
  • Do take a look at rephrased [switch labels](https://stackoverflow.com/a/52238221/1746118)... – Naman Sep 08 '18 at 18:34

2 Answers2

7

Try this:-

switch (key) {
        case 1:
        case 2:
        case 3:
        case 4: 
            Payment();
            break;

        default:
            System.out.println("Choosen an Invlid option");
            break;
        }
vinay chhabra
  • 587
  • 3
  • 7
0

Since you are doing Integer comparison here, you could use Map to reduce the comparison to only one condition. Something like below

    Map<String, Integer> map = new HashMap<>();
    map.put("1", 1);
    map.put("2", 2);
    map.put("3", 3);
    map.put("4", 4);

    void movie() {
    int m;
    System.out.println("Choose the movie :");
    System.out.println("1.BAHUBALI\n2.SHIVAAY\n3.DANGAL\n4.AIRLIFT");
    m = sc.nextInt();

    if (map.containsKey(m)) {
        Payment();
    }
    else {
        System.out.println("Choosen an Invlid option");
    }
}

Map.containsKey : Returns true if this map contains a mapping for the specified key.

So, initially we are putting the value that we are expecting from the user in Map object and then, checking if the actual user input is present in the object using containsKey. If it is then call, Payment() else, println some message

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41