java 在“switch’语中进行字符串与枚举比较的示例:
时间: 2024-02-05 13:12:58 浏览: 69
Java中Switch用法代码示例
5星 · 资源好评率100%
以下是Java中在`switch`语句中进行字符串与枚举比较的示例:
字符串比较:
```java
String str = "hello";
switch(str) {
case "hello":
System.out.println("Hello World!");
break;
case "bye":
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid input!");
}
```
枚举比较:
```java
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day day = Day.MONDAY;
switch(day) {
case MONDAY:
System.out.println("Today is Monday!");
break;
case TUESDAY:
System.out.println("Today is Tuesday!");
break;
case WEDNESDAY:
System.out.println("Today is Wednesday!");
break;
case THURSDAY:
System.out.println("Today is Thursday!");
break;
case FRIDAY:
System.out.println("Today is Friday!");
break;
case SATURDAY:
System.out.println("Today is Saturday!");
break;
case SUNDAY:
System.out.println("Today is Sunday!");
break;
}
```
在Java 7之前,`switch`语句只支持整数类型、字符类型和枚举类型的比较。在Java 7中,可以使用字符串进行比较。
阅读全文