• 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);
                }
            }
        }
    }
    All that work will definitely pay off
  • 相关阅读:
    同一部电脑配两个git账号
    在span中,让里面的span垂直居中用这个
    三张图搞懂JavaScript的原型对象与原型链
    vue2.0 生命周期
    js中__proto__和prototype的区别和关系?
    【转】css 包含块
    【转】BFC(block formating context)块级格式化上下文
    javascript中函数的5个高级技巧
    toString() 和 valueOf()
    桌面图标列表排列小工具
  • 原文地址:https://www.cnblogs.com/afangfang/p/12442782.html
Copyright © 2020-2023  润新知