Switch Statement gives Incompatible Types error

前端 未结 5 1048
长发绾君心
长发绾君心 2020-12-11 03:25

I am trying to compile and I get this error:

enigma/Rotor.java:30: incompatible types found : java.lang.String required: int     switch(name){
1 error


        
相关标签:
5条回答
  • 2020-12-11 03:33

    You cannot switch over a String instance, only int (and byte/char/short, but not long/double), unless you have Java7+. Your best option now is to change to if else statements, like so:

    if("B".equals(string)) {
        //handle string being "B"
    } else if("C".equals(string)) {
        //handle string being "C"
    } else ...
    

    For more info on switching, see the Oracle tutorial. They mention the Java7 String functionality:

    In Java SE 7 and later, you can use a String object in the switch statement's expression.

    0 讨论(0)
  • 2020-12-11 03:41
    switch(name)
    

    switch statement with String is supported from Java7 onwards only.

    I guess the compiler version you are using is less than Java7

    Options:

    1. You need to either upgrade to Java7
    2. Change switch statement to if/else
    3. Use int in switch instead of String
    0 讨论(0)
  • 2020-12-11 03:47

    In Java, you can only do a switch on byte, char, short, or int, and not a String.

    0 讨论(0)
  • 2020-12-11 03:51

    If you are using maven project then simply you can add following piece of code to ypur pom.xml and resolve your problem :

     <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    0 讨论(0)
  • 2020-12-11 03:53

    switch accepts a String from java 7. prior to java 7 only int compatible types (short,byte,int, char) can be passed as switch arguments

    0 讨论(0)
提交回复
热议问题