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");
                }
            }
        }
1
  • Do take a look at rephrased switch labels... Commented Sep 8, 2018 at 18:34

2 Answers 2

7

Try this:-

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

        default:
            System.out.println("Choosen an Invlid option");
            break;
        }
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

can you explain shortly?
@AniketJadhav Updated my answer. Kindly have a look

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.