15

I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.

  • for A, I want to do statement_1 and statement_3.
  • for B, I want to do statement_2 and statement_3.
  • for C, I want to do nothing

if I use if-else statement, it will look like the following:

 if ( not C){
    do statement_3

   if B
      do statement 2
   else if A
      do statement 1

 }

If I want to use switch statement to do the same thing, I have some trouble.

switch (variable){
case A:  do statement_1
case B: do statement_2
// how to do statement 3 here?  
}

I am trying to avoid the duplicated codes. So I am thinking that how to make the codes as simple as I can.

UPDATE 1:

  1. to make my codes/question more clear, I just want to make my codes as simple/clear as I can, that is why I want to use switch statement instead of if-else. Also, I heard that switch-statement is usually faster than if-else. (I am not 100% sure though).

  2. I want to use switch-case because Case A, B, C are enum type. they are not variable. Sorry about the confusion.

  3. each statements are more than 10 lines of codes. That is why I do not want to do the followings:

    switch (enum variable) {
    case A:
      statement1
      statement3
     break;
    case B:
      statement2
      statement3
     break;
    

    }

6
  • This code won't work, because Java 6 and older expects a value of a primitive type. Java 7 can dealt that with Strings. Commented Jul 23, 2013 at 15:48
  • 2
    switch is no good - you can't skip over cases, which is what you'd have to do to avoid coding the call to statement_3 twice Commented Jul 23, 2013 at 15:49
  • 9
    what's wrong with if? If a switch is not the right tool, don't use it. Most of the time, it's not the right tool. Commented Jul 23, 2013 at 15:49
  • I think the if is fine too... Commented Jul 23, 2013 at 15:51
  • 1
    Or Replace Conditional with Polymorphism and get rid of the if / switch Commented Jul 23, 2013 at 15:54

9 Answers 9

26

i would recommend to define exactly what staments should be executed:

switch (variable){
    case A: 
        statement_1();
        statement_3();
        break;
    case B: 
        statement_2();
        statement_3();
        break;
}

for Update-3:

create methods for those 10 lines:

public void statement_1() {
    //your 10 lines of code
}

if you're always executing statement_3, except for case C you can go with if/else-blocks as you wrote them.

but in my honest opinion: define EXACTLY what has to be done in which case if you have a small amount of cases. it is easier to read for others

Sign up to request clarification or add additional context in comments.

Comments

3

You can do this:

switch (variable){
  case A:  do statement_1; do statement_3; break;
  case B:  do statement_2; do statement_3; break;    
}

Comments

1

Why not nest the switch into the if statement? there is no-repeat code this way.

if(!C){
    statement_3;
    switch(variable){
    case A:
        statement_1;
        break;
    case B: 
        statement_2;
        break;
}

or make use of both the if-statement and the switch?

if(!C){
    statement_3;
}
switch(variable){
case A:
    statement_1;
    break;
case B: 
    statement_2;
    break;

2 Comments

but why use a switch with 2 cases and mix it all up? you don't gain performance or anything. it might be confusing for other developers
Because the question referred to using a switch statement. If it is only 2 or 3 cases, then the if-elseif-else is the way to go. but if there is a grouping of statements that all share the same code, say a couple dozen times but not under one scenario, why repeat the code when you can have it executed before the switch (as long as a certain condition is not met)?
0

I often find introducing enums adds clarity. Here I imagine each enum is an issue which can be resolved through a number of processes:

enum Issue {
  A {
    void handleIt () {
      statement_1();
      statement_3();
    }
  },
  B {
    void handleIt () {
      statement_2();
      statement_3();
    }
  },
  C {
    void handleIt () {
      // Do nothing.
    }
  },
  D {
    void handleIt () {
      A.handleIt();
      B.handleIt();
    }
  };

  abstract void handleIt();
}

Note here that you get the added benefit of being able to handle certain issues using the solutions of other issues (see my D enum).

Comments

0

If a case has more than 2-3 statements it's bette(from point of view of readability and clean code) to extract them as separate methods:

switch (variable){
    case A: handleCaseA(); break;
    case B: handleCaseB(); break;
    default: handleDefaultCase(); break;
}

Comments

0
switch (variable) {
case A:  
do statement_1;
do statement_3;
break;
case B:
do statement_2;
do statement_3;
break;
}

1 Comment

Excessive promotion of a specific product/resource may be perceived by the community as spam. Take a look at the help center, specially What kind of behavior is expected of users?'s last section: Avoid overt self-promotion. You might also be interested in How do I advertise on Stack Overflow?
0

With Java 12 switch-expressions you can do it nicely as follows:

switch (variable) {
        case A -> statement_1();
                  statement_3();
        case B -> statement_2();
                  statement_3();
};

Comments

-1

When you use "case," use a switch statement first, and make sure you've got an initialized variable in it. Here's an example.

Use an initialized variable: i.e.

(String s=sc.nextLine();)

        switch (s) {
        case "Pepperoni":
            System.out.println("Pepperoni? Nice choice. Please wait............Ding! Here's your pepperoni pizza. Enjoy, and thanks for using the Local Pizzeria!");
        case "Cheese":
            System.out.println("Cheese? Okay! Soft cheese it is! Please wait............Ding! Here's your cheese pizza. Enjoy, and thank you for using the Local Pizzeria!");
            break;
        case "Mushrooms":
            System.out.println("Mushrooms? Veggie person, right? OK! Please wait............Ding! Here's your mushroom pizza. Enjoy, and thanks for using the Local Pizzeria!");
            break;
        case "Beef Bits":
            System.out.println("Beef bits? Like meat? Alright! Please wait............Ding! Here's your beef bit pizza. Enjoy, and thank you for using the Local Pizzeria!");

            break;
        case "Spicy Buffalo Chicken":
            System.out.println("Spicy buffalo chicken? Way to spice things up! Please wait............Ding! Here's your spicy buffalo chicken pizza. Enjoy, and thank you for using the Local Pizzeria!");
            break;
        case "Exit":
            System.out.println("See you soon!");
        }
    }

Comments

-2

Here u must use if statement in this way because in switch there are normally default value also.

    if (letter == 'A' || letter == 'B') { System.out.println("Statement 3 ");}
switch (letter) {
            case 'A':
                System.out.println("Statement 1 ");
                break;

            case 'B':
                System.out.println("Statement 2 ");
                break;

            case 'C':
                System.out.println();
                break;
            default:
                System.out.println("You entered wrong value");
}       

Comments

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.