Reputation: 1671
I want to have a switch statement like the following:
switch (something)
{
case 1:
int a = 3;
...
break;
case 2:
int a = 4;
....
break;
}
This does not work because a can not be redefined in that scope. I see the following options:
I don't really like any of those four. Which of those is the way to go, or am i missing the best solution?
I saw questions like this one, which suggest using braces, but they are not about the best way to do it, but about getting it to work at all.
Upvotes: 0
Views: 5008
Reputation: 1033
I am guessing you are catching any exception with an illegalstateexception and using a default block.
default:
doSomething();
break;
The oracle style guide does not use braces. It also says that a falls through comment should be added wherever a statement has no break.
However, anything with more than one line can be wrapped in braces with no performance penalty, for readability and reliability. The braces tell the compiler to create a new scope and execute that code as a block. If all you do is change a, then it is not really necessary. If you can write your switch case statement on one line without braces, do it. Many things in java don't do braces in one line instances including if statements.
Next, you can redefine any variable you need to re-use or set in the statements outside of the switch statement. This would be the best practice to minimize continual instantiation of your integers.
If there is more then one line,you should try making a few methods then, go with:
int a=0;
switch (something)
{
case 1:{
a = 3;
...
break;
}
case 2:{
a = 4;
....
break;
}
default:
{
try{
throw new IllegalStateException();
}catch(IllegalStateException e)
{
e.printStackTrace();
}
}
}
Upvotes: 2
Reputation: 313
You can also use Map:
Map<Integer, Integer> caseMap = new HashMap<Integer, Integer>() {{
put(1, 3);
put(2, 4);
}};
int a = caseMap.get(something);
Upvotes: 0
Reputation: 61536
The braces is the right way to do it. {} creates a new scope, which is exactly what you want.
Upvotes: 1