java switch无效,无法在java中获取Switch案例的行为

本文探讨了 Java 中 switch 语句的正确使用方法,并通过一个具体的示例代码解释了为何缺少 break 语句会导致 case 条件穿透,进而产生意外的结果。文章还介绍了如何避免此类问题并给出了正确的代码实现。

I have written small code in java 6

public class TestSwitch{

public static void main(String... args){

int a = 1;

System.out.println("start");

switch(a){

case 1:{

System.out.println(1);

case 3:

System.out.println(3);

case 4:

System.out.println(4);

}

case 2:{

System.out.println(2);

case 5:

System.out.println(5);

case 7:

System.out.println(7);

}

}

System.out.println("end");

}

}

Output: start 1 2 end

My editor is showing orphaned case for 'case 3' and 'case 5'.Still it is running

and showing output.

Does Nastated cases like concept is there in Java?

And Why it is giving above output? rather i thought it will be 'start 1 end'

Your response will be greatly appreciated!!

解决方案

Switch replaces if else's but switch syntax != If else syntax.

You forgot to put break after each case.

So conditions under fall through.

Example:

case 0:

mColor.setText("#000000");

break;

The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

public static void main(String... args){

int a = 1;

System.out.println("start");

switch(a){

case 1:

System.out.println(1);

break;

case 2:

System.out.println(2);

break;

case 3:

System.out.println(3);

break;

case 4:

System.out.println(4);

break;

case 5:

System.out.println(5);

break;

case 7:

System.out.println(7);

break;

default:

System.out.println("nothing");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值