在Java中,switch语句可以用于处理字符串比较。从Java 7开始,switch语句支持字符串类型。以下是一个使用switch语句处理字符串比较的示例:
public class StringSwitchExample {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("It's Monday, the start of the workweek.");
break;
case "Tuesday":
System.out.println("It's Tuesday, second day of the week.");
break;
case "Wednesday":
System.out.println("It's Wednesday, middle of the week.");
break;
case "Thursday":
System.out.println("It's Thursday, almost weekend.");
break;
case "Friday":
System.out.println("It's Friday, the end of the workweek.");
break;
case "Saturday":
System.out.println("It's Saturday, weekend!");
break;
case "Sunday":
System.out.println("It's Sunday, time to relax.");
break;
default:
System.out.println("Invalid day");
}
}
}
在这个示例中,我们使用了一个名为day的字符串变量,并将其与不同的字符串值进行比较。根据day的值,程序将输出相应的消息。注意,每个case后面都有一个break语句,这是为了防止程序继续执行下一个case。如果省略了break语句,程序将执行下一个case,这种现象称为case穿透(case fall-through)。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。