0

I've heard that you can use switch on strings, but Im not getting it to work. ToDo would in this case be a user input String, but my compiler tells me "int cannot be converted into String". Can anybody tell me what I'm doing wrong?

class Comands {
  public Comands () {} 

  public void doSomething (String toDo){

    while (!(toDo.equals("quit"))) {
      switch (toDo) {
        case 1: toDo.equals("right");
        System.out.println("go right");
        break;

        case 2: toDo.equals("left");
        System.out.println("go left");
        break;
      }
    }
  }
}
2

2 Answers 2

3

Like @Hovercraft Full Of Eels mentioned, you are comparing your string with integer in case 1:, this should contain a string like this:

...
case "left":
    // sysout();
    break;
case "right":
    // sysout();
    break;
...
Sign up to request clarification or add additional context in comments.

Comments

1
 switch (toDo) {
    case "right":
    System.out.println("go right");
    break;

    case "left":
    System.out.println("go left");
    break;
  }

Note: Only in Java SE 7 and later, you can use a String object in the switch statement's expression.

More info here.

3 Comments

Do you know if it is possible to do ignoreCase somehow?
@stian You need to use if statements if you want to ignore case.
@stian It's not possible to use ignoreCase, but you can do switch (toDo.toLowerCase()) so that you know your string will be lower case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.