gpt4 book ai didi

java - 如何让 switch case 在 Java 中接受多种数据类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:12:51 24 4
gpt4 key购买 nike

虽然使用 Java switch case,它只接受 char 和 int,但我想提供字符串 case。如何做到这一点?

最佳答案

你不能在 switch-case 中有字符串(目前)。 It's on its way in Java 7.

目前接受的类型包括char, byte, short, int, Character ByteShortInteger 或枚举类型。

来自 Java 语言规范:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type (§8.9), or a compile-time error occurs.

...

All of the following must be true, or a compile-time error will result:

  • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
  • No switch label is null.
  • No two of the case constant expressions associated with a switch statement may have the same value.
  • At most one default label may be associated with the same switch statement.

关于java - 如何让 switch case 在 Java 中接受多种数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2987556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com