1

I'm a beginner in Android Dev. I've just met this problem with a switch case statement on a string :

String str = "Hello";
switch (str) {
    case "Hello":
       System.out.println("case 1");break;
    default:
       System.out.println("default");break;
}

Eclispse Logs :

Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted Home.java

So i'm going to Project properties --> Java Compiler and i set the JDK to 1.7 and applied it. But now eclipse tails me to fix properties which comeback to 1st problem...

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties.

How can i fix it to use my switch case ?

Thanks

5
  • you can fix only using an integer to switch Commented Jul 19, 2013 at 12:58
  • Right click on your project in your eclipse. Goto Android tools. Click Fix Project Properties. Commented Jul 19, 2013 at 12:59
  • You can not pass string in switch statement Commented Jul 19, 2013 at 12:59
  • docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html. check the java docs Commented Jul 19, 2013 at 13:00
  • Click project in your eclipse project->properties->java compiler-> and change the compiler compilence level 1.7 Commented Jul 19, 2013 at 13:06

4 Answers 4

4

You need to pass numeric value or character value in switch statement. Ex.

char str = 'A';
switch (str) {
    case 'A':
       System.out.println("case 1");break;
    default:
       System.out.println("default");break;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Yes switch statements with the String class are introduces in Java 1.7. But Android works with 1.6 sorry. Check the docs for what types you can use. I don't know the case but Enums and switch statements works really well

Comments

0

Lower your compiler version to 1.6 in eclipse properties. Android doesn't support all of 1.7 yet.

enter image description here

Comments

0

To make explicit the case in the switch you can use enums

public enum helloEnum {
    HELLO, HOLA, CIAO
}


public class EnumTest {
    helloEnum mHello;

    public EnumTest(helloEnum mHello) {
        this.mHello = mHello;
    }

    public void sayHello() {
        switch (mHello) {
            case HELLO:
                System.out.println("hello");
                break;

            case HOLA:
                System.out.println("hola");
                break;

            case CIAO
                System.out.println("ciao");
                break;

            default:
                System.out.println("hello");
                break;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.