Loops: For,while and do
There are three kinds of circular control statements in Java, they are: for statements, while statements, and do statements, respectively, describing the structure of these three statements.
1:for Cycle
The format of the For statement is:
for (初始化语句; 条件语句; 控制语句)
{
语句1 ;
语句2 ;
....
语句n ;
}
A For statement is executed in the order that the initialization statement is executed first; then test the conditional statement, if the condition is true, EXECUTE statement 1 to statement N, then execute the control statement, then test if the conditional statement is set up, and repeat the procedure if it is set up until the condition is not true. Such as:
for (i=0;i<10;i++) ...;
int i,a[]=new int[10];
for (i=0,i<10;i++) a[i]= 0;
This code assigns all elements in an integer array a to 0.
You can describe your variable in the head of the For Loop, and the last expression can be omitted, but be sure to change the value of the variable in the statement, such as:
for (int i=0;i<=10;) i+=i;
For loops, initialization statements, conditional statements, and control statements can be omitted, but the semicolon cannot be omitted. For example:
int i =0 ;
for (; ; ;)
{
if i>10 break ;
i = i +1 ;
}
When a "conditional statement" is omitted from the For loop, the procedure in the FOR statement {} must be removed from the for loop when a condition satisfies, otherwise a dead loop is formed
2:while Cycle
The while loop and the for loop are similar in the format:
while (条件语句)
{
语句1 ;
语句2 ;
....
语句n ;
}
执行while时,先测试“条件语句”,如果条件成立,则执行语句1到语句n,直至条件不成立时调处循环。
int i=0 ;
while (i<10)
{
i++ ;
System.out.println("Hey!.get me out of here!:);
}
3:do ... while loop
Do ... the format of the while Loop statement is:
do
{
语句1 ;
语句2 ;
....
语句n ;
}
while (条件语句) ;
do ...while 语句的功能是首先执行语句1到语句n,然后进行条件测试,如果条件成立,则继续执行语句1到语句n,否这跳出循环。如:
boolean test=false;
do
{
......
}
while(test);
This control is not commonly used, but it is sometimes very important to use to note the semicolon at the end of the while statement.