2.6.3循环结构
代表语句:while,do while,for
while语句格式:
while(条件表达式)
{
执行语句;
}
练习。
class While
{
public static void main (String[] args)
{
/*
首先定义初始化表达式
while(条件表达式)
{
循环体 (执行语句);
}
*/
int x =1;// x=1是在内存当中产生一个变量块,名称叫做x并赋值为1。
while (x<3)//当程序读到这里的时候,就开始循环。
{
System.out.println("x="+x);//x=1,x=1,x=1.
x++;//++x也可以。先加后加没有区别。
}
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
do while语句格式:
do
{
执行语句
}
while(条件表达式);
class While
{
public static void main (String[] args)
{
int x =1;
do
{
System.out.println("x="+x);
x++;
}
while(x<3);
/*
while:先判断条件,只有条件满足才执行循环体。
do while:先执行循环体,再判断条件,条件满足,再继续执行循环体。
简单一句话:do while:无论条件是否满足,循环体至少执行一次。
*/
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
for循环:
for(初始化表达式;循环条件表达式;循环后的操作表达式)
{
执行语句;
}
class While
{
public static void main (String[] args)
{
for(int x =0;(1) x<3;(2)(5)(8) x++(4)(7))
{
System.out.println("x="+x);(3)(6)
}
}
}