Switch Statement gives Incompatible Types error

前端 未结 5 1055
长发绾君心
长发绾君心 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.

提交回复
热议问题