while循环
while是最基本的循环,他的结构为:
while( 布尔表达式){ //循环内容 }
只要布尔表达式为true,循环就会一直执行下去。
我们大多数情况是会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环。
少部分情况需要循环一直执行,比如服务器的请求响应监听等。
循环条件一直为true就会造成无限循环【死循环】,我们正常的业务编程中应该尽量避免死循环。会影响程序性能后者造成程序卡死崩溃!
1 package com.xl.struct; 2 3 public class WhileDemo01 { 4 public static void main(String[] args) { 5 //输出1~100 6 int i = 0; 7 8 while (i<100){ 9 i++; 10 System.out.println(i); 11 } 12 } 13 14 }
1 package com.xl.struct; 2 3 public class WhileDemo02 { 4 public static void main(String[] args) { 5 //死循环 是不对的 6 while (true){ 7 System.out.println("11"); 8 //等待客户端连接 9 //定时检查。。。 10 } 11 } 12 }
1 package com.xl.struct; 2 3 public class WhileDemo03 { 4 public static void main(String[] args) { 5 //计算1+2+3+...+100=? 6 int i = 0;//定义一个初始值 7 int sum = 0;//总和 8 while (i<=100){ 9 sum = sum +i; 10 i++;//每次加完以后 i 自增 1 11 } 12 13 System.out.println(sum); 14 } 15 }
1 package com.xl.struct; 2 3 public class WhileDemo033 { 4 5 public static void main(String[] args) { 6 /** 使用while输出1-10 7 * 8 * int i = 0; 9 * while (i<10){ 10 * i++; 11 * System.out.println(i); 12 * } 13 */ 14 /** 求1-100所有数的和 15 * int i = 0, sum = 0; 16 * while (i<=100){ 17 * sum = sum +i; 18 * i++; 19 * // System.out.println(sum); //输出语句放在这里 显示相加过程 20 * } System.out.println(sum);//输出语句放在这里 显示最终结果 21 * 22 */ 23 24 } 25 26 }

浙公网安备 33010602011771号