Java技术_Java千百问(0019)_java中如何循环执行

点击进入_更多_Java千百问


java中如何循环执行

首先,我们看看循环是什么

1、循环是什么

当我们需要多次执行同样的代码段,通常被称为一个循环
Java有非常灵活的三种循环机制:
while 循环
do...while 循环
for 循环

2、什么是while循环

while循环可以按照特定的次数重复执行任务。
语法:

while(Boolean flag)
{
//代码段
}
在执行时,如果flag的结果为true,则循环中的代码段将被执行。直到flag的结果为false,循环执行停止,继续执行循环代码的后续代码。
要注意,while循环的关键点是循环可能永远不会运行。当flag结果为 false,循环体将被跳过,在while循环之后的第一个语句将被执行。
例子:

public class Test {

public static void main(String args[]) {
int x = 10;

while( x < 15 ) {
System.out.println("value of x : " + x );
x++;
}
}

}
这将产生以下结果:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

3、什么是do...while 循环

do ... while循环类似于while循环,不同的是一个do ... while循环是保证至少执行一次
语法:

do
{
//Statements
}while(Boolean flag);
循环方式与while循环大体一致。不同的是,flag表达式出现在循环的结尾,在循环中的语句执行后才会判断flag是否为ture,所以代码段至少会执行一次

例子:

public class Test {

public static void main(String args[]){
int x = 10;

do{
System.out.println("value of x : " + x );
x++;
}while( x < 8 );
}
}
这将产生以下结果:
value of x : 10

4、什么是for循环

for循环可以可以指定执行次数,控制任务执行次数是方便的一件事(当然while和do while也可以实现)。
语法:

for(initialization; Boolean flag; update)
{
//Statements
}
执行过程:
1、initialization首先被执行,并且仅执行一次。这个步骤可声明和初始化任何控制循环的变量。如不需要声明,则用写一个";"即可。
2、判断flag值。如果是true,则执行循环体。如果是false,则循环体不执行,跳出循环继续执行后续代码。
3、若flag为true,执行循环体后,会执行update语句,该语句允许变更任何循环变量。这个语句可以为空, 写一个";"即可。
4、在执行完update语句后,继续第二步操作,产生循环。直到flag为false,则循环终止。
例子:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 15; x = x+1) {
System.out.println("value of x : " + x );
}
}
}
这将产生以下结果:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

5、什么是加强版for循环

Java5之后才有该语法,用来遍历集合体使用的循环。
语法:

for(declaration : expression)
{
//Statements
}
expression为一个可以遍历的集合体,declaration为每次遍历的集合中的值。集合全部遍历完成,则跳出循环。理论上循环次数与集合的size一致。
例子:

public class Test {

public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("
");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}

这将产生以下结果:

10,20,30,40,50,
James,Larry,Tom,Lacy,

点击进入ooppookid的博客


你可能感兴趣的:(java,while,while,循环,for,do)