loop statement in java

There is a way in java that is specially used for repeated execution of certain code, that is, the loop statement;

The loop statements in the java system are: for loop, while loop, do while loop

for loop:

Format: for(loop initial value; loop condition; loop modulation) {loop body}

Rules of use:

When the for loop is executed in the java system, the initial value of the loop will be executed first, and then it will be judged whether the loop condition is true. is true, if it is true, continue to loop until the for loop is jumped out when the loop call is false;

Variation of the for loop:

(1) for (loop initial value; loop condition; loop modulation) {loop body}, loop initial value; loop condition; loop modulation is not necessary but two ";" must exist;

(2) The forEach loop, also known as the enhanced for loop, is dedicated to outputting all elements in arrays and collections

Format: for (variable type variable: array/collection) {loop body}

Rules of use:

Take an element from the array/collection, assign the element to the variable, and then execute the loop body. After the loop body is executed, take out an element again, assign the element to the variable, and execute the loop body again until all elements are taken. ;

Note: The data type of the variable must be the same as the data type of the collection/array

while loop

Format:

while(condition){loop body}

Rules of use:

When executing the while loop, first judge whether the condition is true, if it is true, the loop body will be executed, when the loop ends, it will be judged again whether the loop condition is true, if it is true, the loop body will be executed, and so on until the condition is false jump out

do while loop

Format:

do{loop body}while(condition); 

Note that the ";" after the while condition must be added

Rules of use:

Execute the loop body first, and then judge whether the loop call is true when the loop body is executed. If the condition is true, the loop body will be executed again; it ends when the loop condition is false

for while do-while的区别:

for loops are often used for loops with a certain number of loops; while loops are usually used for loops with an indeterminate number of loops;

while first judges the loop condition and then executes the loop body, do-while loop executes the loop body first, and then judges the loop condition; therefore: the while loop may not execute once, and the do-while loop executes the loop at least once;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326069834&siteId=291194637