2

I'd like to ask if anyone knows how can I use the same array in a switch with different values for the different cases without getting error. I have this code:

    String [] measures;

        switch(option){
                    case "Distance":
                        measures= {"Quilometers(km)", "Meters(m)"};
                        break;
                    case "Temperature":
                        measures= {"Celsius(ºC)", "Fahrenheit(ºF), "Kelvin(K)"};
                        break;
(...)

I'm getting the error "Array initializer is not allowed here" where I have measure={...}

But if I change the code and write inside each case,

String [] measures= {...}

I get the error "Variable measures is already defined in the scope". Can you please help?

porthfind
  • 1,581
  • 3
  • 17
  • 30

3 Answers3

6

You can't initialize array with just braces { and } when you are not declaring the variable. But you can't re-declare measures because it has already been declared in the same block.

You need to explicitly use new String[] before the braces. Try

measures = new String[] {"Quilometers(km)", "Meters(m)"};

and likewise for your other cases.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

Just say measures = new String[] {" instead of measures= {"....

Hille
  • 4,096
  • 2
  • 22
  • 32
0

Firstly, the String[] measures is not initialised. You should add in values in the array with String measures={...} or measures=new String[size];and then some values. Secondly, and more importantly, Strings can not be used properly in a switch-case construct. It only tests equality and should be used only for intand char. Cheers!

Daman Arora
  • 87
  • 2
  • 6
  • 2
    String has been supported in switch since JDK 7. See [Strings in switch Statements](http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html): "The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method..." – Patricia Shanahan Jan 31 '15 at 00:57