2

Say I was taking user input and then based on that called some method corresponding to the input:

public void userPrompt() {
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    
    if (input.equals("a")) {
        callMethodA();
    } else if (input.equals("b")) {
        callMethodB();
    } else if (input.equals("c")) {
        callMethodC();
    }

    // check all the possible commands

    } else {
        System.out.println("Enter a valid command");
    }
}

Is there a better way to do this without resorting to a bunch of if-else statements? It just looks bad and I don't know another way to do this. Everything that I come up with using loops or arrays filled with the valid commands and looping through if input matches, just ends up looking as bad as the if statements.

2
  • Java didn't used to support switching on strings, but it has since version 7. See this answer in particular for the simplest solution. Commented Sep 8, 2021 at 2:15
  • 2
    @JohnKugelman As of Java 8, the simplest solution is usually Map<String, Runnable>. Commented Sep 8, 2021 at 2:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.