Switch Statement and Strings

This question already has an answer here:

  • Why can't I switch on a String? 14 answers

  • As far as I know, this is okay:

    public static void sortData(short days[], String name[]) {
        char choice;
        Scanner kd = new Scanner(System.in);
    
        System.out.println("a. Sort by Namenb. Sort by Day");
        choice = kd.next().toCharArray()[0];
    
        switch (choice) {
        case 'a':
            // do something
            break;
        case 'b';
            // do something else
            break;
        }
    }
    

    Not tested


    You could define a list of strings for your accepted choices and use indexOf to find the entered input. After that you can use the index in your switch .

    Like this

    List<String> options = Arrays.asList("name", "day", "color", "smell");
    switch (options.indexOf(choice)) {
    case 0: // name
        ...
    case 1: // day
        ...
    ... // etc
    default: // none of them
    }
    

    However, using the numbers is not very readable.

    Another idea: define an enum and use valueOf(choice) . In this case you have to catch an IllegalArgumentException for non matching inputs.

    enum Options {
        name, day, color, smell
    }
    

    and then

    try {
        switch (Options.valueOf(choice)) {
        case name: ...
        case day: ...
        // etc
        }
    } catch (IllegalArgumentException ex) {
        // none of them
    }
    

    or, finally, you switch to Java 7 ;-)

    链接地址: http://www.djcxy.com/p/84516.html

    上一篇: C#和Java之间的主要区别是什么?

    下一篇: 切换语句和字符串