目录
Day 9:While 语句的基本使用方法
Task:
while 语句本质上比 for 更基础, 因此可以替代后者. 但 for 在很多时候更方便.
break 语句又出现了, 上次是在 switch 语句里. 都是表示跳出当前代码块.
一、基础知识及案例分析
1. 关于 While 语句
由于在 Day7-Day8 的任务中已经比较多次的使用过 while 语句了,熟悉程度较高;加上在学习 switch,for 语句后也有对应的专题总结,基础知识这里略过。
唯一值得注意的是:
while 和 for 的区别主要在:for 常用于已知具体需要循环多少次,while 常用于未知具体循环次数,但知道结束条件。这个说法是比较感性的,需要读者在编码过程中切实体会。
2. 程序分析
本次测试在累积求值的基础上,增加结束条件:不超过某数。具体逻辑与 for 类似,这里不做展开,仅仅给出对应代码和运行结果。
二、代码及测试
代码如下:
package basic;
/**
* This is the ninth code. Names and comments should follow my style strictly.
*
* @author: Changyang Hu joe03@foxmail.com
* @date created: 2025-05-08
*/
public class WhileStatement {
/**
*
* @Title: main
* @Description: The entrance of the pragram.
*
* @param args Not used now
*
* @return void
*/
public static void main(String args[]) {
whileStatementTest();
}// Of main
/**
*
* @Title: whileStatementTest
* @Description: The sum not exceeding a given value
*
* @return void
*/
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\nAlternatice 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 while
}// Of class WhileStatement
运行结果如下:
拓展:流程控制语句专题补充
小结
相比于 for 循环语句,while 常用于已知结束条件,未知循环具体次数的情景。同时,while 还有一个常见用法:while(true),使得某功能持续运行,可以通过 break 来跳出循环。