温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-17 10:49:18 来源:亿速云 阅读:222 作者: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教学视频

结果:

345
int 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语句和循环语句的使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI