首页 > 其他分享 >while循环

while循环

时间:2023-01-10 23:33:54浏览次数:38  
标签:int while 循环 100 public 表达式

循环结构

  • while循环
  • do...while循环
  • for 循环

在Java5中引入了一种主要用于数组的增强型for循环。

while循环

  • while循环是最基本的循环,它的结构为:

    while( 布尔值表达式 ){
        //循环内容
    }
    
  • 只要布尔值表达式为true,循环就会一直执行下去。

  • $\color{red}{大多数情况是会让循环停止下来的,需要一个让表达式失效的方式来结束循环。}$

  • 少部分情况需要循环一直执行,比如服务器的请求响应监听等。

  • 循环条件一直为true就会造成无限循环(死循环),我们正常的业务编程中应该尽量避免死循环。会影响性能或者造成程序卡死崩溃!

  • 思考:计算1+2+3+4+...+100=?

package com.earl.struct;

public class WhileDemo01 {
    public static void main(String[] args) {
        //输出1-100
        int i = 0;
        while(i<100){
            i++;
            System.out.println(i);
        }
    }
}

package com.earl.struct;

public class WhileDemo03 {
    public static void main(String[] args) {
        //计算1+2+3+4+...+100=?
        int i = 0;
        int sum = 0;
        while (i<=100){
            sum = sum + i;
            i++;
        }
        System.out.println(sum);
    }
}

标签:int,while,循环,100,public,表达式
From: https://www.cnblogs.com/blogearl/p/17041680.html

相关文章