Variation of While loop when Do-while loop
The syntax is as follows:
do{
Loop body
Statement (group);
}while (cyclic continuation condition);
If the statements in the loop need to be executed at least once, then we recommend using the Do-while loop.
For loop
The following common forms are commonly used to write loops:
i = InitialValue; Initializing loop control variables
while (I < endvalue) {
Loop body
...
i++; modifying loop control variables
}
You can simplify the above loops with a For loop:
for (i = initialvalue; i < Endvalue; i++) {
Loop body
...
}
Print Welcome to java!100 times with a for loop
for (int i = 0; i <; i++) {
System.out.println ("Welcome to java!");
}
Note: If you omit the loop continuation condition in the For loop, it is implicitly assumed that the loop continuation condition is true.
for (;;) {
Do something
}
Equivalent to:
for (; true;) {
Do something
}
Equivalent to:
while (true) {
Do something
}
What kind of loop to use:
1) If the number of repetitions is known, a For loop is used
2) If the number of repetitions cannot be determined, a while loop is used
3) If executed at least once, replace the while loop with the Do-while loop.
PackageWelcome;ImportJava.util.Scanner;/** If the statement in the loop needs to be executed at least once, it is recommended to use the Do-while loop*/ Public classTestdowhile { Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); intsum = 0; intdata; Do{System.out.print ("Enter an integer, and if you enter 0 The program will exit:"); Data=In.nextint (); Sum+=data; } while(Data! = 0); System.out.println ("The sum is" +sum); }}
Java Learning Note 15