Question

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.

Was it helpful?

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

OTHER TIPS

You can only do so in Java7, as shown here, your other alternative is to use if statements. If you want to see what Java version you are running, typing java -v or java --version in your console should give you what version you have.

In JDK 7 we can use String comparison in switch. In early java version like (6,4,..). We cannot use String in switch statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top