1

I'm trying to use a switch statement in a Android Application. This switch statement is testing the value of a String, and then based of that changing the value of another String.

String s1 = "a" then String s2 = "1"

I keep getting an error that says I need to change the compliance to 1.7. After I do that, I then get an error that says I need to change the compliance to 1.6.

Is there a way to fix this? or can anyone think of a work around for this?

Just_Some_Guy
  • 330
  • 5
  • 24
  • Can you post your code please? – Christian Tapia Dec 29 '13 at 20:06
  • You can't switch on strings pre-java 7. What Java version do you have? And what is your code exactly? – Jeroen Vannevel Dec 29 '13 at 20:08
  • http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java. I guess android still does not support java 7 – Raghunandan Dec 29 '13 at 20:09
  • Before Java 7 (not yet supported by Android) you can use switch only to compare integers... :( This is not Visual Basic! – Phantômaxx Dec 29 '13 at 20:16
  • http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Using-sourceCompatibility-1.7. As of build tools 19 java 7 is supported – Raghunandan Dec 29 '13 at 20:29
  • well, I updated everything and its still not working. But I know my version of Java supports it because I was able to use strings in switch statements when doing this a a regular Java App, so... I'm not sure. – Just_Some_Guy Dec 29 '13 at 22:08

4 Answers4

7

Java does not support String in switch/case earlier java 7. But if you use java 6 you can achieve the desired result by using an enum.

private enum Fruit {
apple, carrot, mango, orange;
}

String value; // assume input
Fruit fruit = Fruit.valueOf(value); // surround with try/catch

switch(fruit) {
    case apple:
        method1;
        break;
    case carrot:
        method2;
        break;
    // etc...
}
Kostya Khuta
  • 673
  • 2
  • 7
  • 21
1

Using String comparison with equals() instead of switch on Strings (which is available in Java 7) could look like this:

//as an example, if s2 equals 'b'
String s2 = "b";

//this uses String's equals() method
if (s1.equals("a")) then {
    s2 = "1";
}
else if (s1.equals("b")) then {
    s2 = "2";
}
else {
    s2 = "3";
} 

Of course, adapt the conditions to your needs.

Melquiades
  • 8,496
  • 1
  • 31
  • 46
0

donot use switch case but rather use if-else with string equals() method. it will help in code compatibility as switch with strings is only available with jdk 1.7+.

0

You will need to add the below code in your pom.xml if in case it is a maven project.

  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>
Pranav Bhagwat
  • 287
  • 2
  • 11