【问题标题】:Switch Statement and Strings [duplicate]Switch 语句和字符串 [重复]
【发布时间】:2013-04-06 17:54:55
【问题描述】:

如果我让用户从屏幕上的菜单输出中输入字符串中的值。如何将该输入用于 switch 语句?它保持它只能用于int。 例如,如果用户输入 a,我希望它切换到 case 语句并执行操作。很抱歉,如果这令人困惑。

public static void sortData(short days[], String name[]) {
    String choice;
    Scanner kd = new Scanner(System.in);

    System.out.println("a. Sort by Name\nb. Sort by Day");
    choice = kd.next();                       // ????????

    switch (choice) {
    case 1: {                                // ?????????

【问题讨论】:

  • 你不能只获取字符串的第一个字符并使用它而不是字符串吗?据我所知,您可以使用字符进行切换。
  • @11684 我尝试使用 char,它会编译没有任何错误,但是当我输入输入时,它不会显示任何内容。因此我将其更改为字符串。
  • 您使用的是 Java 7 吗?你可以在 case 中使用 String !
  • @user2278109 查看我的回答。

标签: java arrays string switch-statement


【解决方案1】:

据我所知,这是可以的:

public static void sortData(short days[], String name[]) {
    char choice;
    Scanner kd = new Scanner(System.in);

    System.out.println("a. Sort by Name\nb. Sort by Day");
    choice = kd.next().toCharArray()[0];

    switch (choice) {
    case 'a':
        // do something
        break;
    case 'b';
        // do something else
        break;
    }
}

未测试

【讨论】:

  • 我从你的建议中得到了它。发现我的错误。感谢您的意见@11684
【解决方案2】:

您可以为您接受的选择定义一个字符串列表,并使用indexOf 来查找输入的输入。之后,您可以使用switch 中的索引。

像这样

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

但是,使用数字不是很可读。

另一个想法:定义一个枚举并使用valueOf(choice)。在这种情况下,您必须为不匹配的输入捕获 IllegalArgumentException

enum Options {
    name, day, color, smell
}

然后

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

或者,最后,您切换到 Java 7 ;-)

【讨论】:

  • 到目前为止,我们还没有学会 indexOf。还是谢谢!!
  • 很好的答案,比我的好多了。列表的技巧很棒!
猜你喜欢
  • 2012-01-23
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多