I was practicing the other day and I came accross this error with a string for a switch:
Cannot switch on a value of type String. Only int values or enum constants are permitted
I’m not sure how I would fix this so I came here for help. I am using Eclipse. Here is the source, the second VARIABLE (in caps) is where I get the error:
public class Switch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a command: ");
String VARIABLE = input.nextLine();
switch (VARIABLE) {
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped!");
break;
default:
System.out.println("Invalid command");
}
}
}
It’d be cool if someone can help me with this. I’m relatively new to this so I’m not sure if any of this even makes sense.
switchwithStringsare supported from Java 7 onwards. I guess you are using lower version of java you need to either upgrade your java version to 7 (or) remove String from switch and use supported types.Here is oracle tutorial on switch statement.