Wildchild7
Wildchild7

Reputation: 347

Switch statement doesn't work in android project

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

Upvotes: 1

Views: 1326

Answers (4)

Xavier Egea
Xavier Egea

Reputation: 4763

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;
        }
    }
}

Upvotes: 0

s.d
s.d

Reputation: 29436

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

enter image description here

Upvotes: 0

Johannes
Johannes

Reputation: 747

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

Upvotes: 1

Butani Vijay
Butani Vijay

Reputation: 4239

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;
}

Upvotes: 4

Related Questions