switch接受的参数类型

本文介绍了Java中switch语句可以接受的十种参数类型,包括基本数据类型如byte、short、int、char及其对应的包装类,还有String类型及枚举类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

switch接受的参数类型 :

byte;short;int;char;以及相应的包装类Byte;Short;Integer;Character

String;枚举类

共十个类型

### 编程语言中 `switch` 参数支持的数据类型 不同编程语言对于 `switch` 语句的支持存在差异,下面列举几种常见编程语言及其对应的 `switch` 参数所允许使用的数据类型。 #### C/C++ 在C/C++ 中, `switch` 表达式的值可以是整数型(integral types),包括字符(char)、短整形(short int)、长整形(long int)以及无符号版本的这些类型。浮点数值和指针不是合法的选择[^1]。 ```cpp #include <iostream> using namespace std; int main() { char grade = 'B'; switch (grade) { case 'A': cout << "Excellent"; break; case 'B': case 'C': cout << "Well done"; break; default : cout << "Not good"; } } ``` #### Java Java 的 `switch` 可接受 byte、short、char 或者 int 基本数据类型的表达式;从JDK7 开始也能够处理字符串(String) 类型作为条件判断依据,并且还支持枚举(enum)。 ```java public class Main { public static void main(String[] args) { String month = "January"; switch(month.toLowerCase()) { case "january": System.out.println("Month is January"); break; // other cases... default: System.out.println("Invalid Month"); } } } ``` #### JavaScript JavaScript 对于 `switch` 更加灵活一些,除了数字(Number)外还可以直接拿字符串(String), 符号(Symbol)甚至布尔(Boolean)来做匹配操作[^2]。 ```javascript function getDayName(dayNum){ var dayName; switch (dayNum){ case 0: dayName="Sunday"; break; case 1: dayName="Monday"; break; // ... more days ... default : dayName= "Unknown Day!"; } return dayName; } console.log(getDayName(3)); // Outputs: Wednesday or Unknown Day! if invalid input given. ``` #### Python 值得注意的是Python并没有原生提供 `switch-case` 结构,在早期版本里通常会通过字典(dict)模拟实现相似功能。不过自PEP 634 提议并被采纳之后,Python 3.10 引入了模式匹配(pattern matching)语法(`match-case`),这使得编写类似于其他语言中的 `switch` 成为了可能。 ```python def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case _: return "Something's wrong with the internet" print(http_error(404)) # Output: Not found ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值