Java Learning Note 15

Source: Internet
Author: User

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

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.