This question already has answers here:
Why switch is faster than if
(5 answers)
Closed 4 years ago.
I have a variable with values that I want to switch and do actions based on those values. Here is what I currently do:
switch(myvalue)
{
case "action1_category1":
doAction1();
break;
case "action2_category1":
doAction2();
break;
case "action3_category1":
doAction3();
break;
case "action4_category2":
doAction4();
break;
case "action5_category2":
doAction5();
break;
case "action6_category2":
doAction6();
break;
...
}
So, I am thinking why not divide the variable by two categories and do it like this:
if(myvalue.endsWith("category1")
{
switch(myvalue)
{
case "action1_category1":
doAction1();
break;
case "action2_category1":
doAction2();
break;
case "action3_category1":
doAction3();
break;
...
}
}
else
{
switch(myvalue)
{
case "action4_category2":
doAction4();
break;
case "action5_category2":
doAction5();
break;
case "action6_category2":
doAction6();
break;
...
}
}
Will this new approach increase or lower my performance? Thank you.
Well, i'd go towards the first solution for micro optimization .... But now this philosophy is considered evil. Here is a hint
i'm revising for a test and just wondering if you could tell me if i am doing the right thing.
The question asks us to convert this switch statement to and if-else statement:
switch (size) {
case 6:
price = 44.99;
break; case 7:
price = 49.99;
break; case 8:
price = 54.99;
break; case 9:
price = 59.99;
break; case 10:
price = 64.99;
break; default:
}
I've started off by doing this:
if (size==1){
System.out.println("Price is 44.99");
}
else if (size==2){
System.out.print("Price is 49.99");
}
And so on. Can someone let me know if i am doing this correctly or should i be using price instead of size and if so,why?
Thank you!
You have the right idea, but to keep your if-else statements consistent with the switch statement it would be more like
if(size==6){
price = 44.99;
}
else if(size==7){
price = 49.99;
else if(size==8){
price = 54.99;
}
//etc etc
You are going on right track. According to your code it seems that you want to print prize based on size. In leader if else statement only one statement will execute so if your size is 2 it will print 44.99 else if size is three it will print 49.99 etc.
I have a simple switch case statement, and I want to get the current case int.
For example:
case 5:
// some code
break;
I want to get the 5.
Ideas?
Usually to get inside a switch case you need to meet a condition. What you can do is print the condition variable inside the switch case.
int conditionVariable = 0;
At some point in execution the conditionVariable will be set to a value by something in your program. Then the switch case will execute, which will compare conditionVariable to your cases.
switch (conditionVariable)
{
case 5:
// This prints the case number to the logcat.
Log.d("tag", conditionVariable);
break;
. . .
}
scan your keyboard input
store it in int varialble
int currentcase;
switch(currentcase)
{
case 5:
System.out.println("u r in "+ currentcase)
break;
}
I am trying a switch statement to dynamically determine which part of an actionbar dropdown spinner is being selected. This switch statement does not even go to my default case, what am I doing wrong?
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
//restart fragment with selected spinner item's api call
TypedArray mArray = getResources().obtainTypedArray(R.array.spinner_actionbar);
switch(mArray.getResourceId(itemPosition, 0)){
case R.string.spinner_timeline:
break;
case R.string.spinner_profile:
break;
case R.string.spinner_top_posts:
break;
case 0:
break;
default:
break;
}
mArray.recycle();
return false;
}
mArray.getResourceId(itemPosition, 0) returns the position of an arraylist OR 0, and none of my cases not even case 0 is being called
Thanks for any insight, this is using the android framework
You have empty cases in your switch-case block. You want to do something inside each case, besides just break out of the block. For example:
case R.string.spinner_timeline:
System.out.println(R.string.spinner_timeline);
break;
case R.string.spinner_profile:
System.out.println(R.string.spinner_profile);
break;
case R.string.spinner_top_posts:
System.out.println(R.string.spinner_top_posts);
break;
case 0:
break;
default:
System.out.println("default case...");
break;
two cases might be triggered by your code:
case 0 and default
both of those are break so yo cannot tell which is triggered.
R.ids are not position ids most likely
Here, the switch statement is used without making use of why and when to use the switch statement.
A switch statement is useful when you need to select one of several alternatives based on the value of an integer, a character, or a String variable. The basic form of the switch statement is this:
switch (expression)
{
case constant:
statements;
break;
[ case constant-2:
statements;
break; ] ...
[ default:
statements;
break; ] ...
}
In your case, you are using the switch and not telling what to do when you enter the switch-case. As soon as you enter, you leave from the case using the break statement. You are doing the same thing in default case also.
Reference links that you should go through:
Java Switch-case
http://www.dummies.com/how-to/content/switch-statements-in-java.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
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:
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;
}
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;
}
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;
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).
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;
}
switch (variable) {
case A:
do statement_1;
do statement_3;
break;
case B:
do statement_2;
do statement_3;
break;
}
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();
};
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!");
}
}
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");
}