• 技术文章 >Java >Java基础

    java学习之switch语句与循环语句

    王林王林2019-12-16 12:01:02转载1223

    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零基础入门

    以上就是java学习之switch语句与循环语句的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:CSDN,如有侵犯,请联系admin@php.cn删除
    上一篇:java不是内部或外部命令解决方法 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • java判断字符串是否包含某个字符的方法• java显示乱码解决方法• java处理乱码的几种方法• java不是内部或外部命令解决方法
    1/1

    PHP中文网