java中的循环语句有三种:for、while、do..while.
一、for循环
1.语句格式
for(初始化;判断控制;自增){
循环体
}
2.应用场景
在循环次数确定的情况下使用。
3.练习
1.求1-10的和。
public class ForDemo {
/*
* 求数字1-10的和*/
public static void main(String[] args) {
int sum=0;
for(int x=1;x<=100;x++){
sum=sum+x;
}
System.out.println("sum="+sum);
}
}
2.打印100-999之间的水仙花数。
public class ShuiXianHua {
/*
* 打印出100-999之间的水仙花数
* 1.初始值:100;计数器:x<=999或x<1000
* 2.循环体:(1)拆分(2)判断(3)打印*/
public static void main(String[] args) {
for (int x = 100; x <=999 ; x++) {
int gw=x%10;//个位
int sw=x/10%10;//十位
int bw=x/100;//百位
int sum=gw*gw*gw+sw*sw*sw+bw*bw*bw;//各位的三次方和等于原数
if(sum==x){
System.out.println(x);
}
}
}
}
3.打印100-999之间的夹心饼数
public class JiaXinBin {
/*
* 输出100-999之间的夹心饼数
* 1.初始数:100 、循环条件:x<=999、
* 2.分析:拆分、判断、打印*/
public static void main(String[] args) {
for (int x = 100; x <=999 ; x++) {
int gw=x%10;
int bw=x/100;
if(gw==bw){
System.out.println(x);
}
}
}
}
二、While循环
语句格式:
while(循环条件){
循环体
}
用于循环次数不确定的情况。
三、do while
语句格式:
do {
System.out.println("开始");
} while (true);
不常用,第一次先执行循环体中的语句。