Java Syntax Basics (iv)----loop structure of selection structure

Source: Internet
Author: User




First, the cycle structure:



The loop statement can be repeated execution of a piece of code in the case of satisfying the loop condition, which is repeated execution of the code is called the Loop body statement, when the loop body is repeatedly executed, it is necessary to change the loop judgment condition to false at the appropriate time, thus ending the loop, otherwise the loop will continue to form a dead loop.



the composition of the loop statement:


    • Initialization Statement : One or more statements that complete some initialization operations.
    • Judge Condition Statement : This is a Boolean expression that determines whether the loop body is executed.
    • loop Body Statement : This part is the loop body statement, which is what we have to do many times.
    • control Condition Statement : This part is executed once the loop body is finished, and the next loop determines the condition before execution. By controlling the variables in the loop condition, the loop ends at the appropriate time.


Eg: when the console outputs 10 times "HelloWorld",


    • Initialize statement: The definition is initialized to the first time.
    • Judge the condition statement: The number of times cannot exceed 10 times.
    • Loop Body statement: Output "HelloWorld" statement.
    • Control condition Statement: The number of times changes to the next time.


second, loop structure (for Loop statement)



For Loop statement format:



For (initialization statement; judgment condition statement; control condition statement){ Loop body statement; }



Execution process:



A: Execute initialization statement



B: Execute the JUDGMENT condition statement to see if the result is true or false: if False, the loop ends, and if true, continues execution.



C: Execute loop Body statement



D: Execute control condition statement



E: Go back to B continue



Flow chart:






Precautions:



(1) The result of judging a conditional statement is a Boolean type



(2) Circular body statement if it is a statement, curly braces can be omitted, and if it is more than one statement, the curly braces cannot be omitted. Never omit the suggestion.



(3) Generally speaking: there is no semicolon on the left curly brace, there is no left brace for the semicolon



code example:



1. Find the even number between 1-100 and:






/ * Demand: A: Find the sum of 1-100. B: Find the even sum between 1-100 * / class ForTest1 { public static void main(String[] args) { //Find the sum of 1-100. int sum1 = 0; for(int x=1; x<=100; x++) { Sum1 +=x; } System. Out. Println ("sum of 1-100:" + sum1); System.out.println("------------------"); //Find the even sum between 1-100 / / mode 1 int sum2 = 0; for(int x=1; x<=100; x++) { if(x%2 == 0) { Sum2 + = x; } } System. Out. Println ("sum of 1-100 even numbers:" + sum2); System.out.println("------------------"); / / mode 2 int sum3 = 0; for(int x=0; x<=100; x+=2) { Sum3 + = x; } System. Out. Println ("sum of 1-100 even numbers:" + sum3); System.out.println("------------------"); } }



2, the factorial of 5:



/ * Requirement: find the factorial of 5. What is a factorial? N! = n * (n-1)! Rule n! = n*(n-1)*(n-2)*...*3*2*1 The idea of harmony. The thought of seeking factorial. * / class ForTest2 { public static void main(String[] args) { //Define final result variables Int JC = 1; //The X here actually starts at 2 for(int x=2; x<=5; x++) { JC *=x; } System. Out. Println ("the factorial of 1-5 is:" + JC); } }


3. In the console output all the "Narcissus number":


/ *
Requirement: find the factorial of 5.
What is a factorial?
N! = n * (n-1)! Rule
n! = n*(n-1)*(n-2)*...*3*2*1
The idea of harmony.
The thought of seeking factorial.
* /
class ForTest2 {
public static void main(String[] args) {
//Define final result variables
Int JC = 1;
//The X here actually starts at 2
//for(int x=1; x<=5; x++) 
for(int x=2; x<=5; x++) {
JC *=x;
}
System. Out. Println ("the factorial of 1-5 is:" + JC);
}
}



3. Output all "narcissus number" on the console:


/ *
Requirement: output all "narcissus number" on the console
Analysis:
We all don't know what is "narcissus number". What do you want me to do?
The so-called number of Narcissus refers to a three digit number whose cubic sum of each digit is equal to the number itself.
Example: 153 is a narcissus number.
153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153
A: Three digits tell us the range.
B: Through the for loop, we can get every three digits
But the trouble is how to get the three digit data
How can we get one, ten, one hundred data?
Suppose there is one data: 153
ge:	153%10 = 3
shi: 153/10%10 = 5
bai:153/10/10%10 = 1
qian:x/10/10/10%10
wan:  x/10/10/10/10%10
...
C: Let Ge * Ge * Ge + Shi * Shi * Shi + Bai * Bai compare with this data
If it is the same, output the data in the console.
* /
class ForTest3 {
public static void main(String[] args) {
//Three digits tell us the range.
for(int x=100; x<1000; x++) {
int ge = x%10;
int shi = x/10%10;
int bai = x/10/10%10;
//Let Ge * Ge * Ge + Shi * Shi * Shi + Bai * Bai compare with this data
if(x == (ge*ge*ge+shi*shi*shi+bai*bai*bai)) {
//If it is the same, output the data in the console.
System.out.println(x);
}
}
}
}


Third, loop structure (while loop statement)



While loop statement format:



While (judgment condition statement){ Loop body statement; } Extended format Initialization statement; While (judgment condition statement){ Loop body statement; Control condition statement; }



Note: The conversion can be equivalent to the For loop.



Flow chart:






The difference between a for loop and a while loop:



The For loop and while loop statements can be equivalent conversions, but there are some neighborhoods.



(1) Use the difference:



The variable controlled by the control condition statement can no longer be accessed after the For loop ends, and the while loop will continue to work, if you want to continue using it, use while, otherwise it is recommended for. The reason is that the For loop ends and the variable disappears from memory, which can improve the efficiency of memory usage.



(2) Scene difference:


    • For loop is suitable for a range judgment
    • While loop is suitable for judging the number of ambiguous operations


code example:



The highest mountain in China is Mount Everest: 8848m, I now have a large enough paper, thickness: 0.01m. Excuse me, how many times do I fold to ensure that the thickness is not lower than the height of Mount Everest?






/ * Demand: Xiaofang's mother gives her 2.5 yuan every day, and she will save it, but, Every time it's the fifth day of saving or a multiple of five, she'll spend six yuan, Excuse me, after how many days, Xiaofang can save up to 100 yuan. Analysis: A: Xiaofang's mother gives her 2.5 yuan a day double dayMoney = 2.5; B: She'll save it double daySum = 0; C: Store from day one int dayCount = 1; D: After how many days, Xiaofang can save up to 100 yuan. double result = 100; E: If this day is the fifth day of saving or a multiple of five, she will spend six yuan, Explain to judge the value of daycount, if divide 5, subtract 6 yuan. DaySum = 6; It also implies that if it is not a multiple of five days, the money should be accumulated daySum += dayMoney; F: Because I don't know how many days it is, I use the dead cycle. Once it exceeds 100 yuan, I will quit the cycle. * / class WhileDemo { public static void main(String[] args) { //The money to be saved every day is 2.5 yuan double dayMoney = 2.5; //The initial value of saving money is 0 double daySum = 0; //Store from day one int dayCount = 1; //In the end, if the storage is no less than 100, it will not be stored int result = 100; //Because I don't know how many days it is, so I use the dead cycle, while(true) { / / accumulated money daySum += dayMoney; //Once it's over $100, I quit the cycle. if(daySum >= result) { System. Out. Println ("spent" + daycount + "days to store 100 yuan in total"); Break; } if(dayCount%5 == 0) { //Six yuan DaySum = 6; System. Out. Println ("the first" + daycount + "six yuan for smallpox"); } //Days change DayCount++; } } }


IV. cyclic structure (Do...while loop statement)



Basic format:



Do { Loop body statement; }While ((judgment condition statement);



Extended format:



Initialization statement; Do { Loop body statement; Control condition statement; }While ((judgment condition statement);



Flow chart:









Five, the difference of circular structure and matters needing attention:



Three kinds of circular statements can actually accomplish the same function, that is to say, the equivalent conversion, but there are small differences:


    • The Do...while cycle executes at least one loop body.
    • The For loop and while loop execute the loop body only when the condition is true


1. Precautions:



The write program takes precedence over the for loop, then considers the while loop, and finally considers the Do...while loop.



The following code is a dead loop:


    • while (true) {}
    • for (;;) {}


2, loop nested use: is the loop statement of the loop body itself is a circular statement



(1) Title one: please output a 4-row 5-column star (*) Pattern:



Tip: Outer loop control number of rows, inner loop control number of columns






/ * Requirement: Please output the following shapes * * * * * * * * * * * * * * * * Tip: the number of control lines and columns of the external loop * / class ForForTest01 { public static void main(String[] args) { //From a simple observation, we can see that this is a row of 5, and the number of columns is a changing shape //Let's print out a shape with five rows and five columns for(int x=0; x<5; x++) { for(int y=0; y<5; y++) { System.out.print("*"); } System.out.println(); } System.out.println("--------------"); //We implemented a shape of five rows and five columns //But that's not what we want //What we want is a change in the number of columns //How does the number of columns change? //First row: 1 column y = 0, y < = 0, y++ //Second row: 2 columns y = 0, y < = 1, y++ //The third row: 3 columns y = 0, y < = 2, y++ //The fourth row: 4 columns y = 0, y < = 3, y++ //The fifth row: 5 columns y = 0, y < = 4, y++ //When we look at the change of the external cycle x, it happens to be x = 0,1,2,3,4 //So the final version of the program is as follows for(int x=0; x<5; x++) { for(int y=0; y<=x; y++) { System.out.print("*"); } System.out.println(); } }



(2) Title two: the console output 99 multiplication table:

/ *
Requirement: output the multiplication table in the console.
First, we write the multiplication table:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
...
1*9=9 2*9=18 3*9=27 ...
First of all, we can see that this multiplication table has such a shape:
*
* *
* * *
* * * * *
* * * * *
* * * * *
* * * * * *
* * * * * *
* * * * * * *
Be careful:
'\ X' x means arbitrary, which is called shifting characters.
'\ t' position of a tab (tabtab key)
Enter
'\ n' wrap
* /
class ForForTest02 {
public static void main(String[] args) {
for(int x=0; x<9; x++) {
for(int y=0; y<=x; y++) {
System.out.print("*");
}
System.out.println();
}
System.out.println("--------------");
//To use the data, we start with 1
for(int x=1; x<=9; x++) {
for(int y=1; y<=x; y++) {
System.out.print(y+"*"+x+"="+y*x+"\t");
}
System.out.println();
}
}
}
Operation effect:
6、 Jump control statement:
As we have said before, goto in Java is reserved word and cannot be used at present. Although there is no goto statement to enhance the security of the program, it also brings a lot of inconvenience. For example, I want to end a cycle when it knows a certain step, and I can't do this now. In order to make up for this defect, Java provides break, continue and return to realize the jump and interrupt of control statement.
Break interrupt
Continue
Return return
1. Break:
Use scenario of break:
In the switch statement of the selection structure
In the loop statement (if judgment is added to the loop statement)
Note: it is meaningless to leave the existence of use scenarios
The role of break:
A: Jump out of single layer loop
B: Jump out of multi-level loop
To achieve this effect, one must know something. Statement with label. Label names should conform to Java Naming Rules
Format:
Tagnames: statements
Code example:
/ *
Control jump statements:
Break: interrupt
Continue: continue
Return: Return
Break: break means
Usage scenario:
A: In the switch statement
B: Loop statement.
(if judgment is added to the loop statement)
Note: it is meaningless to leave the above two scenes.
How to use it?
A: Jump out of single layer loop
B: Jump out of multi-level loop
To achieve this effect, one must know something. Statement with label.
Format:
Tagnames: statements
* /
class BreakDemo {
public static void main(String[] args) {
//Interrupt outside switch or loop
//break;
//Jump out of single layer loop
for(int x=0; x<10; x++) {
If (x = = 3) {
Break;
}
System.out.println("HelloWorld");
}
System.out.println("over");
System.out.println("-------------");
//Jump out of multi-level loop
wc:for(int x=0; x<3; x++) {
nc:for(int y=0; y<4; y++) {
If (y = = 2) {
//break NC;
Break WC;
}
System.out.print("*");
}
System.out.println();
}
}
}
On line 38, we add a tag to the outer loop called WC, and then jump out of the tag on line 42.
Operation effect:
Note: in actual development, it is almost impossible to use the function of jump to multi-layer loop.
2. Jump control statement (continue):
Use scenario of continue:
In a loop statement
It's meaningless to leave the use scenario
The difference between continue and break:
Break out of single layer loop
Continue jumps out of one loop and enters the next execution.
The effect is as follows:
Interview questions

for(int x=1; x<=10; x++) {
If (x%3==0) {
//Code here
}
System. Out. Println ("java learning");
}
Fill in a line of code in line 4 of the above code to meet the following conditions:
I want to output two times in the console: "java learning" break;
I want to output 7 times in the console: "java learning" continue;
I want to output 13 times in the console: "java learning" system. Out. Println ("java learning");
3. Jump control statement (return)
The return keyword is not used to jump out of the loop body. The more commonly used function is to end a method, that is, to exit a method and jump to the method called by the upper layer.
Let's be clear: the function of return is not to end the loop, but to end the method.
The effect is as follows:
Loop statement combined with break exercise:
Interview question: Xiaofang's mother gives her 2.5 yuan every day, and she will save it. However, whenever this day is the fifth day or multiple of 5, she will spend 6 yuan. How many days can Xiaofang save 100 yuan.
Code implementation:
/ *
Demand: Xiaofang's mother gives her 2.5 yuan every day, and she will save it, but,
Every time it's the fifth day of saving or a multiple of five, she'll spend six yuan,
Excuse me, after how many days, Xiaofang can save up to 100 yuan.
Analysis:
A: Xiaofang's mother gives her 2.5 yuan a day
double dayMoney = 2.5;
B: She'll save it
double daySum = 0;
C: Store from day one
int dayCount = 1;
D: After how many days, Xiaofang can save up to 100 yuan.
double result = 100;
E: If this day is the fifth day of saving or a multiple of five, she will spend six yuan,
Explain to judge the value of daycount, if divide 5, subtract 6 yuan.
DaySum = 6;
It also implies that if it is not a multiple of five days, the money should be accumulated
daySum += dayMoney;
F: Because I don't know how many days it is, I use the dead cycle. Once it exceeds 100 yuan, I will quit the cycle.
* /
class WhileDemo {
public static void main(String[] args) {
//The money to be saved every day is 2.5 yuan
double dayMoney = 2.5;
//The initial value of saving money is 0
double daySum = 0;
//Store from day one
int dayCount = 1;
//In the end, if the storage is no less than 100, it will not be stored
int result = 100;
//Because I don't know how many days it is, so I use the dead cycle,
while(true) {
/ / accumulated money
daySum += dayMoney;
//Once it's over $100, I quit the cycle.
if(daySum >= result) {
System. Out. Println ("spent" + daycount + "days to store 100 yuan in total");
Break;
}
if(dayCount%5 == 0) {
//Six yuan
DaySum = 6;
System. Out. Println ("the first" + daycount + "six yuan for smallpox");
}
//Days change
DayCount++;
}
}
}
Fundamentals of Java syntax (4) -- loop structure of selection structure

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.