java开关的用法_Java字符串开关(switch用法)

开关表达式(switch-expression)使用String类型。 如果switch-expression为null,则抛出NullPointerException。

大小写标签必须是字符串文字。不能在 case 标签中使用String变量。

以下是在switch语句中使用String的示例。

public class Main {

public static void main(String[] args) {

String status = "off";

switch (status) {

case "on":

System.out.println("Turn on");

case "off":

System.out.println("Turn off");

break;

default:

System.out.println("Unknown command");

break;

}

}

}

上面的代码生成以下结果。

Turn off

switch比较

String类的equals()方法执行区分大小写的字符串比较。

public class Main {

public static void main(String[] args) {

operate("on");

operate("off");

operate("ON");

operate("Nothing");

operate("OFF");

operate("No");

operate("On");

operate("OK");

operate(null);

operate("Yes");

}

public static void operate(String status) {

// Check for null

if (status == null) {

System.out.println("status cannot be null.");

return;

}

status = status.toLowerCase();

switch (status) {

case "on":

System.out.println("Turn on");

break;

case "off":

System.out.println("Turn off");

break;

default:

System.out.println("Unknown command");

break;

}

}

}

上面的代码生成以下结果。

Turn on

Turn off

Turn on

Unknown command

Turn off

Unknown command

Turn on

Unknown command

status cannot be null.

Unknown command

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值