for 循环 结合 switch语句的使用(java)

来源:百度知道 编辑:UC知道 时间:2024/05/18 19:03:57
public class Switchtest
{
int i=0,w=0;
public Switchtest()
{
for(;i<=5;i++)
{
switch(i)

{case 3:w+=1;
case 0:w+=1;
case 1:w+=1;continue;
case 2:w+=1;
case 4:w+=1;
default:w+=2;
}
System.out.println(" "+w);
}

}
public static void main(String []args)
{
Switchtest stest=new Switchtest();

}

}
运行出来是 7 13 15
想知道 具体的思路~谢谢

这是switch语句的一种特性,case语句中如果没有加入break的话会继续执行的,会把下面的所有的case的语句执行完,然后离开switch.除非中间出现break,他会跳出switch,然后执行switch后面的程序。

你这段程序的执行顺序是:
执行case 0
执行case 0中的w += 1;(由于没有break,所以会继续执行下面的case语句)
执行case 1;
执行case 1中的w += 1;
执行continue;(此处出现continue,所以不会执行后面的case语句)
执行case 1;
执行case 1中的w += 1;
执行continue;;(此处出现continue,所以不会执行后面的case语句)
执行case 2
执行case 2中w += 1;
执行case 4
执行case 4中w += 1;
执行case default
执行case default中w += 2;(到此处switch执行完)
执行System.out.println(w is:7)
执行case 3
执行case 3中w += 1;
执行case 0
执行case 0中w += 1;
执行case 1;
执行case 1中w += 1;
执行continue;
执行case 4
执行case 4中w += 1;
执行case default
执行case default中w += 2;(到此处switch执行完)
执行System.out.println(w is:13)
执行case default
执行case default中w += 2;
执行System.out.println(w is:15)
for循环执行完毕,整个程序执行完

我想你主要问的是这个吧:当执行完switch(0)后,continue,然后本次循环结束,就是说switch(0)也结束了,但是在执行for(i=1)和switch(1)