java switch语句套循环_java中switch语句和循环语句的使用

java中switch语句和循环语句的使用

发布时间:2020-06-17 10:49:18

来源:亿速云

阅读:121

作者:Leah

这篇文章运用简单易懂的例子给大家介绍java中switch语句和循环语句的使用,代码非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、switch语句int a = 1,b =2;

switch(a+b){

case 1:

System.out.print(1);

case 3:

System.out.print(3);

case 4:

System.out.print(4);

default:

System.out.print(5);

}

1、先执行 a+b 得出值 3

2、找到相对应case 3,然后继续向下

3、执行执行所有的语句,因为没有 break

在线免费视频教程推荐:java教学视频

结果:345int a = 2, b = 34;

switch(a + b){

case 5:

System.out.println(5);

break;

case 6:

System.out.println(6);

break;

default:

System.out.println(12);

}

1、执行 a + b ,得出 36

2、执行 default

结果:12

判断月份Scanner a = new Scanner(System.in);

System.out.print("please input a month:");

int month = a.nextInt();

switch(month){

case 1: case 2: case 3:

System.out.println("Spring");

break;

case 4: case 5: case 6:

System.out.println("Summer");

break;

case 7: case 8: case 9:

System.out.println("Autumn");

break;

case 10: case 11: case 12:

System.out.println("Winter");

break;

default:

System.out.println("fasle");

}Scanner a = new Scanner(System.in);

System.out.print("please input a month:");

int month = a.nextInt();

switch(month){

case 1:

case 2:

case 3:

System.out.println("Spring");

break;

case 4:

case 5:

case 6:

System.out.println("Summer");

break;

case 7:

case 8:

case 9:

System.out.println("Autumn");

break;

case 10:

case 11:

case 12:

System.out.println("Winter");

break;

default:

System.out.println("fasle");

}

两个方式一样,但switch语句内,的多个语句,即语句块,并不需要加花括号,因为碰到break语句跳出,否则继续执行下去。

2、循环语句

求1000以内的素数int j;

for (int i = 0; i < 1000; i++) {

for (j = 2; j < i; j++)

if (i % j == 0)

break;

if (j == i)

System.out.println(i);

}

结果:2

3

5

当然上面犯了一个明显的错误,最外层的循环应该是<=1000,虽然并不影响什么,但要铭记。for (int i = 0; i < 1000; i++) {

if(i == 2)

System.out.println(2);

for (int j = 2; j < i; j++) {

if(i % j == 0)

break;

if(j == i - 1 )

System.out.println(i);

}

}

关于java中switch语句和循环语句的使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


版权声明:本文为weixin_39574065原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。