Java:打印switch语句的选项

Dan*_*ous 2 java switch-statement

我有一些代码,我要求用户输入一个字符串输入,然后我将其与一个开关中的某些选项进行匹配,以便程序知道如何继续.

 switch (algorithm.toLowerCase()) {

        case "selection sort":
            // Selection sort stuff
            break;

        case "insertion sort":
            // Insertion sort stuff
            break;

        case "exit":
            // Default, just exit.
            System.exit(0);
Run Code Online (Sandbox Code Playgroud)

但是对于不是我自己的用户,他们不知道他们可以输入的选项.一个显而易见的解决方案是在打印语句中进行硬编码,告诉他们选项,但我想知道在捕获用户输入之前是否有一种以编程方式显示我的开关的情况.

我正在考虑某种包含选项的数据结构,但我不确定哪种方式最好地利用Java并符合其标准实践.

Men*_*ena 7

您的switch声明无法提前知道选项,部分原因是您使用硬编码常量来比较输入.

考虑使用enum替代(使用有限的"硬编码"选项的标准方式),并使用switch与您的enum.

String诸如用户输入之类的内容进行比较时,您可以调用valueOf,或者对于具有空格的值,您可以拥有自己的转换方法(因为Java中的变量名称不能包含空格).

就像是:

enum Options {
    SELECTION_SORT("selection sort"),
    INSERTION_SORT("insertion sort"),
    EXIT("exit");
    String value;
    Options(String value) {
        this.value = value;
    }
    static Options forInput(String input) {
        // TODO handle null/empty
        for (Options option: values()) {
            // ignoring case in comparison here
            if (option.value.equalsIgnoreCase(input)) return option;
        }
        return null; // or throw IllegalArgumentException
    }
    // minimal print of all available values as expected input
    static void printAll() {
        for (Options o: values()) {
            System.out.println(o.value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

... 然后...

switch (Options.forInput(algorithm)) {
    case SELECTION_SORT: {// TODO}
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

...可以跟随调用Options.printAll()以向用户显示可用的输入选项.