Aniket Jadhav
Aniket Jadhav

Reputation: 578

is it possible to use the multiple cases in "if condition" to access the same function

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");
                }
            }
        }

Upvotes: 0

Views: 79

Answers (2)

Ashishkumar Singh
Ashishkumar Singh

Reputation: 3600

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

Upvotes: 0

vinay chhabra
vinay chhabra

Reputation: 587

Try this:-

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

        default:
            System.out.println("Choosen an Invlid option");
            break;
        }

Upvotes: 7

Related Questions