Day-08增强for循环、break、continue


增强for循环、break、continue

一.增强for循环

java增强for循环语法格式如下:

for(声明语句:表达式)
{
    //代码句子
}

声明语句:声明新的局部变量,该变量的类型必须和数组元素的类型匹配,其作用域限定在循环语句块,其值与此时数组元素的值相等

表达式:表达式是要访问的数组名,或者是返回值为数组的方法

例:

package com.struct;

public class ForDemo04 {
    public static void main(String[] args) {
        int[] numbers={10,20,30,40,50};//定义了一个数组

        //遍历数组的元素
        for (int x:numbers){
            System.out.println(x);
        }
    }
}

二.break与continue

break例:

package com.struct;

public class BreakDemo {
    public static void main(String[] args) {
        int i=0;
        while (i<100){
            i++;
            System.out.println(i);
            if (i==10){
                break;
            }
        }
        System.out.println("123");
        //输出结果
//        1
//        2
//        3
//        4
//        5
//        6
//        7
//        8
//        9
//        10
//        123
    }
}

continue例:

package com.struct;

public class ContinueDemo {
    public static void main(String[] args) {
        int i=0;
        while (i<100){
            i++;
            if (i%10==0){
                System.out.println();
                continue;
            }
            System.out.print(i);
            //输出结果
//            123456789
//            111213141516171819
//            212223242526272829
//            313233343536373839
//            414243444546474849
//            515253545556575859
//            616263646566676869
//            717273747576777879
//            818283848586878889
//            919293949596979899
        }
    }
}

三.练手:打印三角形

package com.struct;

public class TestDemo01 {
    public static void main(String[] args) {
        //打印三角形   5行

        for (int i = 0; i <= 5; i++) {
            for (int j = 5;j >= i; j--) {
                System.out.print(" ");
            }
            for (int j=1;j<=i;j++){
                System.out.print("*");
            }
            for (int j=1;j