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.
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:
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).
I want to use switch-case because Case A, B, C are enum type. they are not variable. Sorry about the confusion.
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;
}
The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char.
Example: Java switch Statement The variable is compared with the value of each case statement. Since the value matches with 44, the code of case 44 is executed. size = "Large"; break; Here, the size variable is assigned with the value Large .
So, printf(“2+3 makes 5”) is executed and then followed by break; which brings the control out of the switch statement. Other examples for valid switch expressions: switch(2+3), switch(9*16%2), switch(a), switch(a-b) etc.
13) What is the output of Java program with SWITCH? 14) What is the output of Java program below? Explanation: It is allowed to write expressions that result in constant values.
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
You can do this:
switch (variable){
case A: do statement_1; do statement_3; break;
case B: do statement_2; do statement_3; break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With