for循环结构的使用

/*
 for循环格式:
    for(①初始化条件; ②循环条件 ;③迭代部分){
    //④循环体
    }
    执行顺序:①-②-④-③---②-④-③-----直至循环条件不满足 退出当前循环
 * */
public class TestFor {
    public static void main(String[] args) {
        System.out.println("Hello World");
        System.out.println("Hello World");
        System.out.println("Hello World");
        System.out.println("Hello World");
System.out.println("-----------分割线----------");
        for (int i = 0; i < 4; i++) {
            System.out.println("Hello World");
        }
    }
}

练习1:输出100以内的所有偶数。及其所有偶数的和 与它们的个数

public class Test5 {
    public static void main(String[] args) {
        int sum = 0;
        int count = 0;
        for (int i = 1; i <= 100; i++) {// 遍历100以内的自然数
            if (i % 2 == 0) {
                System.out.println(i);
                sum += i;
                count += 1;
            }
        }
        System.out.println("总和:" + sum);
        System.out.println("总个数:" + count);
    }
}

练习2:程序FooBooHoo, 1-150循环 并每行打印一个值,

             每个3的倍数行打印foo,5的倍数行打印boo,7的倍数行打印hoo

public class FooBooHoo {
    public static void main(String[] args) {
        for (int i = 1; i <= 150; i++) {
            System.out.print(i);
            if (i % 3 == 0) {
                System.out.print("foo");
            }
            if (i % 5 == 0) {
                System.out.print("boo");
            }
            if (i % 7 == 0) {
                System.out.print("hoo");
            }
            System.out.println();
        }
    }
}

注意:先不用换行  一个循环结束在换行。

练习3: 输出所有的水仙花数,指的是一个三位数,其个位上的数字立方和等于其本身

public class ShuiXianHua {
    public static void main(String[] args) {
        for (int i = 100; i <= 999; i++) {
            int j1 = i / 100;
            int j2 = (i - j1 * 100) / 10;
            int j3 = i % 10;
            if (i == j1 * j1 * j1 + j2 * j2 * j2 + j3 * j3 * j3) {
                System.out.println(i);
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/afangfang/p/12442782.html