1. while循环
1、 while循环是最基本的循环,他的基本结构为:
while(布尔表达式){//循环结构}
★ 只要布尔表达式为 ture, 循环就会一直执行下去。
while循环适用于不知道具体循环次数,只知道循环达到某个条件可以执行时使用
public class Test {public static void main(String args[]) {int x = 10; //定义变量x的值为10;while( x < 20 ) { //循环条件:x的值小于20为true、大于20为falseSystem.out.print("x= : " + x ); //输出x的值;x++; //x 自增(+1);System.out.print("\n"); //输出换行;}}}
2. do…while循环
1、与while循环不同的是,do…while循环至少会执行一次;
2、循环条件后面的分号不能掉;
do{//语句}while(布尔表达式)
★ 布尔表达式在循环体的后面,所以语句块在检测布尔表达式之前已经执行了。 如果布尔表达式的值为 true,则语句块一直执 行,直到布尔表达式的值为 false<br /> do...while循环适用于不知道循环具体执行次数,只知道满足某个条件继续执行或执行结束,并且循环肯定执行一次时使用
public class Test {public static void main(String args[]){int x = 10;do{System.out.print("x= : " + x ); //输出x的值;x++;System.out.print("\n");}while( x < 20 ); //判断x大于小于20;}}
案例:随机猜数字
public class GuessDemo{public static void main(String[] args){//设置要猜的数int number=(int)((Math.random()*10+1); //使用随机数生成1到10之间的整数int guess;System.out.println("猜一个介于1到10之间的数");do{System.out.println("请输入您猜测的数字:");Scanner sc = new Scanner(System.in);guess=sc.nextInt();if(guess>number){System.out.println("太大!");}else if(guess<number){System.out.println("太小!");}}while(number!=guess);System.out.println("您猜中了!答案为"+number);}}
3. for循环
1、最先执行初始化步骤。可以声明一种类型,可初始化一个或多个循环控制变量,也可以是空语句。<br /> 2、执行一次循环后,更新循环控制变量。
for(初始化; 布尔表达式; 更新) {//代码语句}
★ 从for循环的结构来看,三个表达式会依次执行到,执行的顺序也是固定的,所以for循环适用于循环次数固定的场景
public static void main(String[] args){int sum=0;for(int n=1;n<=5;n++){sum= sum+n;}System.out.println(n);System.out.println("sum="+sum);}
注意:局部变量只在定义它的大括号内有效;
