Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate local variable in switch statement [duplicate]

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?

like image 475
Someone Avatar asked Mar 13 '14 18:03

Someone


People also ask

How do you solve duplicate local variables?

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).

Can we use case as a variable name in Java?

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.


2 Answers

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)

like image 52
fge Avatar answered Sep 22 '22 19:09

fge


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.

like image 27
rgettman Avatar answered Sep 26 '22 19:09

rgettman