Search code examples
javadrjava

DrJava switch(String) issue


DrJava is having problem compiling a very very simple switch statement.

This is a simple example:

switch (sc.next()) {
  case "abc": output = 0; break;
  case "bcd": output = 1; break;
}

DrJava returns the following message on the first line.

Error: Cannot switch on a value of type java.lang.String. Only convertible int values or enum constants are permitted

SSH Secure Shell has no problem compiling it, and I heard switch(String) is implemented since long time ago. What can I do to fix this issue on DrJava?

*My DrJava is of the newest version.


Solution

  • What is your Java version? Switch statements on strings only started in Java 7.

    Else you will have to use the good old if condition :

    String text = sc.next()
    
    if(text.equals("abc")) {
        output = 0;
    } else if (text.equals("bcd")) {
        output = 1;
    }