I was getting this error using Eclipse.
Duplicate local variable cape
I really don't understand why I was getting such an error. This was my code:
switch (frame) { // frame is an integer
case 0:
Sprite cape = modules.get(Module.CAPE);
//cape.setRegion(region);
cape.translateY(+1);
break;
case 1:
Sprite cape = modules.get(Module.CAPE);
//cape.setRegion(region);
cape.translateY(-1);
break;
default:
throw new IllegalArgumentException(
"Undefined frame number: " + frame);
}
Why is it not true that the cape variable is local to each case, but instead to the switch statement?
The solution is to either rename your second (duplicate) variable to something else (like in the example: b) or keep using the existing variable a (by not declaring it again, i.e. lose the second int in this example).
For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word. Variables in Java are not allowed to contain white space, so variables made from compound words are to be written with a lower camel case syntax.
The whole switch
statement is a code block like any other. But you can create code blocks inside code blocks, so:
case 0: {
// code here
}
case 1: {
// other code here
}
(if the switch
were treated specially in this regard you couldn't be able to do follow through)
Each case is within the same block, specifically, the {}
for the switch
statement. This is the same block even when different cases define the same variable.
Define your own blocks for each case by adding {}
s:
case 0:
{
Sprite cape = modules.get(Module.CAPE);
//cape.setRegion(region);
cape.translateY(+1);
}
break;
case 1:
{
Sprite cape = modules.get(Module.CAPE);
//cape.setRegion(region);
cape.translateY(-1);
}
break;
Or you can simply declare cape
before the switch
so it's in scope there, where you use the reference.
Sprite cape;
switch (frame) { // frame is an integer
case 0:
cape = modules.get(Module.CAPE);
and similarly for case 1.
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