Java loop statement

Source: Internet
Author: User
Tags repetition
Java cyclic statements-general Linux technology-Linux programming and kernel information. The following is a detailed description. Java loop statements include for, while, and do-while. These statements create what we usually call a loop (loops ). You may know that a loop repeats the same set of commands until an ending condition occurs. You will see that Java has a loop structure suitable for any programming.

5.2.1 while statement
While statements are the most basic loop statements in Java. When its control expression is true, the while statement repeatedly executes a statement or statement block. Its common format is as follows:

While (condition ){
// Body of loop
}

Condition can be any Boolean expression. The loop body is executed as long as the conditional expression is true. When the condition is false, program control is passed to the statement line followed by the loop. If only one statement needs to be repeated, braces are unnecessary.

The while LOOP Below starts from 10 and prints 10 "tick" rows ".

// Demonstrate the while loop.
Class While {
Public static void main (String args []) {
Int n = 10;

While (n> 0 ){
System. out. println ("tick" + n );
N --;

}
}
}

When you run this program, it will "tick" 10 times:

Tick 10
Tick 9
Tick 8
Tick 7
Tick 6
Tick 5
Tick 4
Tick 3
Tick 2
Tick 1

Because the while statement calculates the condition expression at the beginning of the loop. If the condition is false at the beginning, the loop body will not be executed once. For example, in the following program, the call to println () has never been executed:

Int a = 10, B = 20;

While (a> B)
System. out. println ("This will not be displayed ");

The body of a while loop (or any other Java loop) can be empty. This is because a null statement (a statement consisting of only one semicolon) is legal in Java syntax. For example, the following program:

// The target of a loop can be empty.
Class NoBody {
Public static void main (String args []) {
Int I, j;

I = 100;
J = 200;

// Find midpoint between I and j
While (++ I <-- j); // no body in this loop

System. out. println ("Midpoint is" + I );
}
}

This program finds the center points of the variables I and j. The output is as follows:

Midpoint is 150

The while loop in this program is executed in this way. Value I auto-increment, value j auto-subtraction, and then compare the two values. If the new value I is still smaller than the new value j, a loop is performed. If I is equal to or greater than j, the loop stops. Before exiting the loop, I will save the median of the original I and j (of course, this program is executed only when I is smaller than j at the beginning ). As you can see, the loop body is not required here. All actions appear in the condition expression itself. In specialized Java code, some short loops that can be processed by the control expression itself do not usually have a loop body.

5.2.2 do-while loop
As you have just seen, if the while loop is a false conditional expression at the beginning, the loop body will not be executed at all. However, a while loop sometimes needs to be executed at least once at the beginning, even if the conditional expression is false. In other words, sometimes you need to test the stop expression after a loop ends, instead of when the loop starts. Fortunately, Java provides the do-while loop. The do-while loop always executes its loop body at least once, because its conditional expression is at the end of the loop. Its common format is as follows:

Do {
// Body of loop
} While (condition );

The do-while loop always executes the loop body first and then calculates the conditional expression. If the expression is true, the loop continues. Otherwise, the loop ends. All Java loops are the same, and the condition must be a Boolean expression. The following is a rewritten "tick" program used to demonstrate the do-while loop. Its output is the same as that of the previous program.

// Demonstrate the do-while loop.
Class DoWhile {
Public static void main (String args []) {
Int n = 10;

Do {
System. out. println ("tick" + n );
N --;

} While (n> 0 );
}
}
Although the loop in this program is technically correct, it can be written more efficiently as follows:

Do {
System. out. println ("tick" + n );
} While (-- n> 0 );

In this example, the expression "-- n> 0" combines the decrease of n value and test whether n is 0 in a single expression. Its execution process is like this. First, execute the -- n statement, decrease the Variable n, and then return the new value of n. This value is then compared with 0. If it is greater than 0, the loop continues. Otherwise, it ends.

The do-while loop is especially useful when selecting menus, Because you usually want to execute the menu loop body at least once. The following program is a simple help system that implements Java selection and repeated statements:

// Using a do-while to process a menu selection
Class Menu {

Public static void main (String args [])
Throws java. io. IOException {
Char choice;

Do {
System. out. println ("Help on :");
System. out. println ("1. if ");
System. out. println ("2. switch ");
System. out. println ("3. while ");
System. out. println ("4. do-while ");
System. out. println ("5. for \ n ");
System. out. println ("Choose one :");
Choice = (char) System. in. read ();

} While (choice <'1' | choice> '5 ');

System. out. println ("\ n ");

Switch (choice ){

Case '1 ':
System. out. println ("The if: \ n ");
System. out. println ("if (condition) statement ;");
System. out. println ("else statement ;");

Break;

Case '2 ':
System. out. println ("The switch: \ n ");
System. out. println ("switch (expression ){");
System. out. println ("case constant :");
System. out. println ("statement sequence ");
System. out. println ("break ;");
System. out. println ("//...");
System. out. println ("}");
Break;

Case '3 ':
System. out. println ("The while: \ n ");
System. out. println ("while (condition) statement ;");
Break;

Case '4 ':
System. out. println ("The do-while: \ n ");
System. out. println ("do {");
System. out. println ("statement ;");
System. out. println ("} while (condition );");
Break;

Case '5 ':
System. out. println ("The for: \ n ");
System. out. print ("for (init; condition; iteration )");
System. out. println ("statement ;");
Break;

}
}
}

Below is a sample output of this program execution:

Help on:

1. if
2. switch
3. while
4. do-while
5.
Choose one:
4
The do-while:
Do {

Statement;
} While (condition );

In the program, the do-while loop is used to verify whether the user has entered a valid choice. If no, the user is required to re-enter. Because the menu must be displayed at least once, the do-while loop is an appropriate statement to complete this task.

For more information, see System. in. read. This is a Java console input function. Although the Java terminal I/O (input/output) method will be discussed in detail in chapter 12th, here we use System. in. read () to read the user's choice. It reads characters from standard input (returns an integer, so the return value choice is defined as character type ). By default, the standard input enters the buffer by row. Therefore, you must press the Enter key before any character you enter is sent to your program.

Java terminal input functions are quite limited and not easy to use. Furthermore, most real Java programs and applets (small applications) have graphical interfaces and are window-based. Therefore, this book does not have many terminal input. However, it is useful in this example. Another point: Because System. in. read () is used, the program must specify the throws java. io. IOException clause. This line of code is necessary to handle input errors. This is part of Java Exception Handling and will be discussed in Chapter 10th.

5.2.3 for Loop
In chapter 1, I used a simple for loop format. As you can see, a for loop is a powerful and flexible structure. The general format of the for Loop is as follows:

For (initialization; condition; iteration ){
// Body
}

If only one statement needs to be repeated, braces are unnecessary.
The for loop is executed as follows. Step 1: When the loop starts, execute the initialization part first. Generally, this is an expression used to set the value of a loop control variable as a counter to control the loop. It is important to understand that the initialization expression is executed only once. Next, calculate the condition value. Condition must be a Boolean expression. It usually compares the cyclic control variable with the target value. If the expression is true, the loop body is executed. If the expression is false, the loop ends. Next, execute the repeating part of the loop body. This part is usually an expression that adds or removes loop control variables. Next, repeat the loop. First, calculate the value of the conditional expression, then execute the loop body, and then execute the repeated expression. This process repeats until the control expression changes to false.

The "tick" program using the for loop is as follows:

// Demonstrate the for loop.
Class ForTick {
Public static void main (String args []) {
Int n;

For (n = 10; n> 0; n --)
System. out. println ("tick" + n );
}
}

Declare the loop control variable in the for Loop

The variables used to control the for loop are often used only for this loop, rather than in other places of the program. In this case, you can declare the variable in the initialization part of the loop. For example, the preceding program is rewritten to declare variable n as an integer in the for loop:

// Declare a loop control variable inside the.
Class ForTick {
Public static void main (String args []) {

// Here, n is declared inside of the for loop
For (int n = 10; n> 0; n --)
System. out. println ("tick" + n );
}
}

When declaring a variable in a for loop, you must remember that the scope of the variable ends after the for statement is executed (therefore, the scope of this variable is limited to the for loop ). Except for the for loop, the variable does not exist. If you need to use loop control variables elsewhere in the program, you cannot declare them in the for loop.

Since loop control variables are not used elsewhere in the program, most programmers declare them in the for loop. For example, the following is a simple program for testing prime numbers. Note that I is not required elsewhere, so the loop control variable I is declared in the for loop.

// Test for primes.
Class FindPrime {

Public static void main (String args []) {
Int num;
Boolean isPrime = true;

Num = 14;
For (int I = 2; I <= num/2; I ++ ){

If (num % I) = 0 ){
IsPrime = false;
Break;

}
}
If (isPrime) System. out. println ("Prime ");
Else System. out. println ("Not Prime ");

}
}

Use commas

You may need to include more than one variable declaration in the initialization and for loop repetition sections. For example, consider the loop section of the following program:

Class Sample {

Public static void main (String args []) {
Int a, B;
B = 4;
For (a = 1;
System. out. println ("a =" + );
System. out. println ("B =" + B );
B --;

}
}
}

As you can see, the loop is controlled by two interacting variables. Because the loop is controlled by two variables, it is useful if both variables can be defined in the for loop, and variable B does not need to be manually processed. Fortunately, Java provides a method to complete this task. To allow two or more variable control loops, Java allows you to declare multiple variables in the initialization part and repetition Part Of The for loop. Each variable is separated by a comma.

Use commas to make the previous for loop more efficient. The rewritten program is as follows:

// Using the comma.
Class Comma {
Public static void main (String args []) {
Int a, B;

For (a = 1, B = 4;
If (I = 10) done = true;

I ++ ;}}

}

In this example, the initialization part and the repetition part are moved out of the for loop. In this way, the initialization part and repetition Part Of The for loop are empty. In this simple example, there is no value in the for loop. Indeed, this style is considered to be quite poor, and sometimes this style is also useful. For example, if the initial condition is defined by a complex expression in other parts of the program, or the change of the cyclic control variable is determined by the action that occurs in the loop body, in addition, this change is an unordered way. In this case, these parts of the for loop can be left empty.

Below is another for loop change method. If the three parts of the for loop are empty, you can create an infinite loop (a loop that never stops ). For example:
For (;;){
//...
}

This loop will always run because there is no condition for terminating it. Although some programs, such as the operating system command processor, require infinite loops, most "infinite loops" are actually loops with special termination requirements. Soon you will see how to terminate this type of loop without using a normal conditional expression.

5.2.5 loop nesting
Like other programming languages, Java allows loop nesting. That is, one loop is in another loop. For example, the following program is nested loop:

// Loops may be nested.
Class Nested {
Public static void main (String args []) {
Int I, j;

For (I = 0; I <10; I ++ ){
For (j = I; j <10; j ++)
System. out. print (".");
System. out. println ();
}
}
}

The output of this program is as follows:

..........
.........
........
.......
......
.....
....
...
..
.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.