简体   繁体   中英

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

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

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

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM