2017.6.28学习小结 - 循环的跳转2

回顾

一、循环的跳转

1.break语句

①不带标签的break

②带标签的break

2.continue语句

①不带标签的continue

②带标签的continue

学习小结

一、循环的跳转

3.return语句

离开return语句所在的方法,可以返回一个值。

语法格式:

return;

reture 返回值;

注:

1.三元运算相当于if...else语句,只有在if...else语句的主体部分很少时才使用;

2.switch中并不是每一个case都需要break语句;

3.三种循环可以互相转换;

4.循环中通常使用半开区间,提高了可读性,即for(int i = 0;i < 10;++i),而非for(int i = 0;i <= 10;++i)

实战习题

1.使用循环控制语句计算“1+2+...+100”的值:

public class P164_7_6_1 {

    public static void main(String[] args) {
        int sum = 0; // 初始化sum和变量
            for (int i = 1; i <= 100; i++) {
                sum += i; // 循环累加100次
            }
        System.out.println("1+2+...+100 = " + sum); // 输出计算值
        }

}

2.随机产生1~12的某一个数,输出相应月份的天数(2月算28天):

public class P164_7_6_2 {

    public static void main(String[] args) {
        double rand = Math.random(); // 随机产生[0,1)的一个double数
        int month = 1 + (int)(12 * rand); // 处理为1~12的随机数
        switch (month) { // 相应月份并输出
        case 1:
            System.out.println(month + "月共有31天");
            break;
        case 2:
            System.out.println(month + "月共有28天");
            break;
        case 3:
            System.out.println(month + "月共有31天");
            break;
        case 4:
            System.out.println(month + "月共有30天");
            break;
        case 5:
            System.out.println(month + "月共有31天");
            break;
        case 6:
            System.out.println(month + "月共有30天");
            break;
        case 7:
            System.out.println(month + "月共有31天");
            break;
        case 8:
            System.out.println(month + "月共有31天");
            break;
        case 9:
            System.out.println(month + "月共有30天");
            break;
        case 10:
            System.out.println(month + "月共有31天");
            break;
        case 11:
            System.out.println(month + "月共有30天");
            break;
        case 12:
            System.out.println(month + "月共有31天");
            break;

        default:
            System.out.println("程序出错!");
            break;
        }
    }

}

3.判断某年是否为闰年:

public class P164_7_6_3 {

    public static void main(String[] args) {
        Scanner scan= new Scanner(System.in); // 实例化一个扫描Scanner类
        System.out.println("请输入4位数的年份:");
        int year = scan.nextInt(); // 获取输入的年份
        if(year % 4 == 0){ // 判断是否被4整除
            System.out.println(year + "年是闰年!");
        }else{
            System.out.println(year + "年不是闰年!");            
        }
    }

}

思考

真是惭愧,昨天没有学习。直接睡着了,睡着了,睡着了......这些天,每天都要外出工作,都是一整天,加上舟车劳顿,确实有些累,我感觉基础又扎实了一些,昨天的进度还是要追的,明天学习数组。造起来!


记于2017年6月28日夜(29日凌晨)

你可能感兴趣的:(2017.6.28学习小结 - 循环的跳转2)