Godz
Godz

Reputation: 31

Switches in Java

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.

Upvotes: 1

Views: 567

Answers (3)

BackSlash
BackSlash

Reputation: 22233

Your code is right, but the String support for switch-case constructs were introduced in java7 (jdk1.7), so your error means that you have an older java version and you have to upgrade it. If you don't want to upgrade your Java, then you'll need to use a multiple if-else construct:

[...]
if(VARIABLE.equals("start")){
    System.out.println("Machine started!");
} else if(VARIABLE.equals("stop")){
    System.out.println("Machine stopped!");
} else {
    System.out.println("Invalid command");
}
[...]

Upvotes: 2

Puce
Puce

Reputation: 38132

In addition to Nambari's answer: You can use if-else constructs with Strings, of course, to have a switch-like logic with Strings.

Upvotes: 3

kosa
kosa

Reputation: 66637

switch (VARIABLE) {

switch with Strings are 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.

Upvotes: 11

Related Questions