day09

Day09 —— While 循环

1. Background

今天是学习java的第9天了,今天学习的内容是while循环。

在我的心里面while循环是比for循环更加简单的存在,一直是把它当作for的下位替代来的。记得我三年前刚学C语言的时候,就只会一个while循环,然后用while循环实现了冒泡排序等等简单排序。可是之后学完for循环之后,写程序几乎没有用过while了,因为for属实好用。

2. Description

今天的代码是用while循环求和,但是Sum不能超过一个最大值,其中求和的value每次自增1.

代码比较简单,整体和C语言相似,所以就直接上代码了。

3.Code

package basic;

/**
 * This is the ninth code.
 * 
 * @author Leo liu lyx1443807042@163.com.
 */

public class Day09 {
    /**
     *******************
     * The entrance of the program.
     * 
     * @param args Not used now.
     *******************
     */
    public static void main(String[] args) {
        whileStatementTest();
    } // Of main

    /**
     *******************
     * The sum not exceeding a given value.
     *******************
     */
    public static void whileStatementTest() {
        int tempValue = 0;
        int tempSum = 0;
        int tempMax = 100;

        // Approach 1.
        while (tempSum <= tempMax) {
            tempValue++;
            tempSum += tempValue;
            System.out.println("tempvalue = " + tempValue + " , tempSum = " + tempSum);
        } // Of while
        tempSum -= tempValue; // 当tempSum大于tempMax时才会跳出循环,与所求不符,故减去最后的加的那个tempValue.
        
        System.out.println("The sum not exceeding " + tempMax +" is: " + tempSum);

        // Approach 2.
        tempSum = 0;
        tempValue = 0; // 此处展示第二种求值方法,为避免上面代码对变量的污染,此处重新初始化变量

        while (true) {
            if (tempSum > tempMax) {
                break;
            } // Of if
            
            tempValue++;
            tempSum += tempValue;
            System.err.println("tempvalue = " + tempValue + " , tempSum = " + tempSum);
        } // Of while
        tempSum -= tempValue;

        System.out.println("The sum not exceeding " + tempMax +" is: " + tempSum);
    } // Of whileStatementTest
} // Of Day09

运行结果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值