- 循环while
While(逻辑表达式){
代码;
}
每次代码执行完毕之后,再次回到while继续循环执行
举例:依次打印1、2、3、4、5
package com.feimao.code; public class While01 { public static void main(String args[]){ int i = 1; while (i <= 5){ System.out.println(i); i = i + 1; } } }
这里面的i = i +1可以写作i++
同时循环变量为i = 1可以作为循环的起点,而i <= 5 可以反向作为循环的终点,循环i++的步幅为1
举例:用while循环写出阶乘 n!=1*2*3*4……*n
package com.feimao.code; /* 求n=10的阶乘n! n!=1*2*3*4……*10 * */ public class While02 { public static void main(String ags[]){ int i = 1; int n = 10; int res = 1; while(i <= n){ res = res * i; i++; } System.out.println(res); } }
上面程序中res 为什么赋值1?
因为是阶乘,res=1的时候,任何数乘以1结果不变
举例:输出所有比10小的奇数
package com.feimao.code; /*按顺序输出所有比10小的奇数*/ public class While03 { public static void main(String ars[]){ int i = 1; int n = 10; while(i < n){ if(i % 2 == 1){ //取模运算 System.out.println(i); } i++; } } }
举例:输入int n,m,输出的m的n次方
package com.feimao.code; /*输入int n,m,输出的m的n次方*/ public class While04 { public static void main(String args[]) { int n = 4; int m = 2; int res = 1; while (n >= 1) { res = res * m; n--; } System.out.println(res); } }
举例:写一个程序分解一个整数的每一位的数字,从个位开始分别输出它的每一位数字
package com.feimao.code; /*写一个程序分解一个整数的每一位的数字,从个位开始分别输出它的每一位数字*/ public class While05 { public static void main(String args[]){ int i= 9527; while(i > 0){ int r = i % 10; int q = i / 10; System.out.println(r); i = q; } } }
举例:蜗牛爬树,白天爬5米,晚上下滑2米,问10米高的树需要几天爬到顶?
package com.feimao.code; /*蜗牛爬树,白天爬5米,晚上下滑2米,问10米高的树需要几天爬到顶?*/ public class While06 { public static void main(String args[]){ int n = 10 , x = 5 , y = 2; int h = 0 , d = 0; while (true){ h = h + x; if(h >= n){ d++; break; } else{ h = h - y; d++; } } System.out.println(d); } }