Java重开第九天-while

while循环

代码展示

总结

while循环

while(判断条件){undefined
循环体
}

Java提供了三种类型的循环语句:while循环,do-while循环和for循环。
while循环在每次循环开始前,先会判断条件是否成立。如果计算结果为true,就把循环体内的语句执行一遍,如果计算结果为false,那就直接跳到while循环的末尾,继续往下执行。
举个例子

public class Main {
    public static void main(String[] args) {
        int sum = 0; // 累加的和,初始化为0
        int n = 1;
        while (n <= 100) { // 循环条件是n <= 100
            sum = sum + n; // 把n累加到sum中
            n ++; // n自身加1
        }
        System.out.println(sum); // 5050
    }
}

在while循环中可以使用break关键字,跳出该循环。

tempValue = 0;
		tempSum = 0;
		while (true) {
			tempValue++;
			tempSum += tempValue;
			System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);

			if (tempMax < tempSum) {
				break;
			} // Of if
		} // Of while
		tempSum -= tempValue;

		System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);

	}// Of whileStatementTest

代码展示

package basic;

/**
 * 
 * 
 * @author Donghao Xu
 */
public class WhileStatement {

	/**
	 *********************
	 * 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 tempMax = 100;
		int tempValue = 0;
		int tempSum = 0;

		// approach 1.
		while (tempSum <= tempMax) {
			tempValue++;
			tempSum += tempValue;
			System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
		} // Of while
		tempSum -= tempValue;

		System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);

		// Approach 2.
		System.out.println("\r\nAlternative approach.");
		tempValue = 0;
		tempSum = 0;
		while (true) {
			tempValue++;
			tempSum += tempValue;
			System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);

			if (tempMax < tempSum) {
				break;
			} // Of if
		} // Of while
		tempSum -= tempValue;

		System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);

	}// Of whileStatementTest
}// Of class WhileStatement

while(true)可作为无限循环,可以由自己循环中的某个条件式来结束。

while(true) {
    语句; 
      if(条件式) 
          break;  // 跳离当前循环
       ...
} 

区分break和continue
1.break

有时候我们想在某种条件出现的时候终止循环而不是等到循环条件为false才终止。

这是我们可以使用break来完成。break用于完全结束一个循环,跳出循环体执行循环后面的语句。

2.continue
continue和break有点类似,区别在于continue只是终止本次循环,接着还执行后面的循环,break则完全终止循环。
可以理解为continue是跳过当次循环中剩下的语句,执行下一次循环。

总结

通过矩阵加法和乘法,把for循环和while循环再次进行回顾。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值