Switchcase支持的类型
时间: 2023-06-18 20:06:40 浏览: 53
在大多数编程语言中,switch case语句支持以下数据类型:
1. 整型(int、long等)
2. 字符型(char、wchar_t等)
3. 枚举类型(enum)
4. 字符串类型(string或char*)
5. 浮点型(float、double等)
但是,不同的编程语言对于支持的数据类型可能存在一定的差异。同时,一些编程语言也可以通过特殊的语法来扩展switch case的支持类型,比如C++11中的支持对于枚举类以及自定义类型的支持。
相关问题
Java switch case支持string类型吗?
是的,从Java 7开始,switch case支持字符串类型。在以前的版本中,switch case仅支持整数类型(int、byte、short、char)和枚举类型。下面是一个使用字符串类型的switch case的示例:
```
String fruit = "apple";
switch(fruit) {
case "apple":
System.out.println("Selected fruit is apple");
break;
case "orange":
System.out.println("Selected fruit is orange");
break;
case "banana":
System.out.println("Selected fruit is banana");
break;
default:
System.out.println("Invalid fruit selection");
}
```
在这个示例中,我们使用字符串类型的变量fruit来切换不同的选项,如果fruit的值与case语句中的字符串值匹配,那么相应的代码块将被执行。
Java switch case支持string类型吗?
从 Java 7 开始,Java 的 switch case 语句支持 String 类型。在 switch 中使用 String 类型时,每个 case 分支都必须是字符串常量或者 final 类型的字符串变量。例如:
```java
String fruit = "apple";
switch(fruit) {
case "apple":
System.out.println("This is an apple.");
break;
case "banana":
System.out.println("This is a banana.");
break;
default:
System.out.println("This is not a fruit.");
}
```
在上面的代码中,我们使用了一个字符串变量 `fruit`,并在 switch 中使用了它。在每个 case 分支中,我们使用了字符串常量来比较。注意,我们必须使用 `break` 语句来结束每个 case 分支,否则会继续执行下一个 case 分支。