Java知识系统回顾整理01基础05控制流程04 for

一、for

比较for和while

   

public class HelloWorld {

    public static void main(String[] args) {

            

        //使用while打印0到4    

        int i = 0;

        while(i<5){

            System.out.println("while循环输出的"+i);

            i++;

        }

            

        //使用for打印0到4    

        for (int j = 0; j < 5; j++) {

            System.out.println("for  循环输出的"+j);

        }

    }

}

   

二、练习--乞丐收入

题目:

天朝有一个乞丐姓洪,去天桥要钱

第一天要了1块钱

第二天要了2块钱

第三天要了4块钱

第四天要了8块钱

以此类推

   

问题: 洪乞丐干10天,收入是多少?

要求效果:

   

官方答案:

public class HelloWorld {

    public static void main(String[] args) {

   

        int moneyEachDay = 0;

        int day = 10;

        int sum=0;

        for (int i = 1; i <= day; i++) {

            if(0==moneyEachDay)

                moneyEachDay = 1;

            else

                moneyEachDay *= 2;            

            sum+=moneyEachDay;        

            System.out.println(i + " 天之后,洪帮主手中的钱总数是: " + sum );

        }

    }

}

   

个人整理答案:

public static void main(String[] args) {

        int getMoneyNumEachday =0;

        int dayNumber = 10;

        int totalGetMoneyNumSum =0;

          

        for (int i =1; i <=dayNumber ; i++) {

            if (getMoneyNumEachday == 0) {

                getMoneyNumEachday = 1;

            }else {

                getMoneyNumEachday *= 2;

            }

            totalGetMoneyNumSum += getMoneyNumEachday;

            System.out.println("第" + i +"天,洪帮主一共乞讨了" + totalGetMoneyNumSum +"元钱 !");

        }

    }

   

posted @ 2019-04-25 20:42  皿哥的技术人生  阅读(466)  评论(0编辑  收藏  举报