当前位置: 首页 > news >正文

【日撸 Java 三百行】Day 9(While语句)

目录

Day 9:While 语句的基本使用方法

一、基础知识及案例分析

二、代码及测试

拓展:流程控制语句专题补充

小结


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 whiletempSum -= 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 whiletempSum -= tempValue;System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);}// Of while
}// Of class WhileStatement

        运行结果如下:

拓展:流程控制语句专题补充

【Java 专题补充】流程控制语句-CSDN博客


小结

        相比于 for 循环语句,while 常用于已知结束条件,未知循环具体次数的情景。同时,while 还有一个常见用法:while(true),使得某功能持续运行,可以通过 break 来跳出循环。

相关文章:

  • 让模型具备“道生一,一生二,二生三,三生万物”的现实实用主义能力
  • SPL量化---SMA(算术移动平均)
  • LLM 推理加速:深度解析 Prefilling 与 Decoding 阶段的优化秘籍
  • 全球首套100米分辨率城市与农村居住区栅格数据(2000-2020)
  • Gradio launch() 方法所有参数说明
  • Missashe计网复习笔记(随时更新)
  • python连接sqllite数据库工具类
  • 运维体系架构规划
  • 执梦为楫,共启中医传承新篇
  • SpringAI框架中的RAG知识库检索与增强生成模型详解
  • RAG 技术详解:如何让大模型更 “懂” 知识库?
  • O2O上门服务如何颠覆传统足浴行业?真实案例分析
  • 5 种距离算法总结!!
  • 详解 c++17 重载类 overload的每一条语句,附实例.
  • LintCode1343-两字符串和,1535-转换成小写字母
  • 强化学习三大基本方法-DP、MC、TD
  • setData执行后操作方法-微信小程序
  • AD 绘制原理图--元件的放置
  • 服务器多客户端连接核心要点(1)
  • 11.多用组合和少继承
  • 招商蛇口:今年前4个月销售额约498.34亿元
  • 图忆|红场阅兵:俄罗斯30年来的卫国战争胜利日阅兵式
  • 对话|蓬皮杜策展人布莱昂:抽象风景中的中国审美
  • 陕西澄城打造“中国樱桃第一县”:从黄土高原走向海外,年产值超30亿
  • 美联储主席:关税“远超预期”,美联储实现目标的进程或被推迟至明年
  • 习近平在俄罗斯媒体发表署名文章