preface
C: in the Java syntax | flow chart of control statements, and “article, check the teacher introduces three kinds of control statements, each control statements has it can solve the problem. For example, sequence control statements can solve “flow” steps, and selection control statements can solve the condition judgment problem.
In this article we’ll look at the last type of control statement: the loop control statement. It can be used to solve repetitive, regular problems in a business.
What is a cycle
life
Circulating: English [circulate;circle]
- To move in a ring, loop, or orbit;
- Run along a zigzag route;
- It is used to run once and then come back and turn again.
- Or to do something repeatedly in succession.
Computer programs are derived from life programs. In life, we go to work, go to school, stick to a habit, etc.
There is even a meme in his daily remarks in the past two years: “The essence of human beings is a repeater.”
The computer
There is a need for loops in life, and there are countless similar needs in computer programs.
In many practical problems, there are many regular repeated operations, so some statements need to be repeated in the program. Loop structure is a process structure that executes a certain program repeatedly under certain conditions, and the program that is repeatedly executed is called loop body (loop operation). [1]
Case requirement: The score of Java test in Xiong University did not reach the target. In order to show their determination to study hard, he decided to write one hundred times “good good study, day day up!”
The teacher really likes such a self-motivated student! So how to use Java code to output “study hard, day day up” 100 times?
There seems to be nothing wrong with it, but if you have Ctrl+C and Ctrl+V, it becomes much easier. But what if today’s ambitious student decides to write it 10,000 times? Even in CV, the amount of code is daunting!
The good news is that the Java language has three looping syntax options, all of which can easily address this need.
The while loop
The while loop is a classic loop structure syntax, not only in the Java language, but also in other programming languages.
grammar
Its syntax, loosely speaking, consists of two components, very similar to the if selection structure.
- The loop condition
- The loop body
while(loop condition) {loop body/loop operation}Copy the code
From the flow chart, we can see that the main difference between it and the selection structure is that when the condition is established and the operation is completed, it will not directly end, but will enter the condition judgment again until the condition is not established.
use
Next we use the case to master the steps.
Case requirement 1: Solve the big problem above.
Analysis of ideas:
-
This case is a repetitive step requirement, which is solved by a circular control statement
-
To apply the while loop, you need to identify the two fixed components of the loop in this case.
- Cyclic conditions:
< = 100
- Loop operation: output “Good good study, day day up”
- Cyclic conditions:
-
Write code using the syntax of the while loop
Loose syntax only considers loop conditions and loop operations. However, in order to let students write code can form a complete step idea, Teacher Cha has made an extension of the grammar step, expanded to four parts, so that you can directly think about the composition of four parts when using the cycle to solve the problem.
Teacher Zha said: these two extra components are actually to complement the use of cyclic conditions.
- Initialize loop variables: Prepare a start variable for the loop condition expression
- The loop condition
- Cycle operation
- Loop exit: Changes a variable in a loop condition expression so that the loop can end at a specified time
-
Check whether it is normal to exit the loop after the service is complete
Code implementation:
// 1. Initialize the loop variable
int i = 1;
// 2. Loop conditions
while (i <= 100) {
// 3
System.out.println("The first" + i + "Times: good good study, day day up!");
// 4. Circulation outlet
// use the variable I as a loop condition, if the value of I does not change, there will be an infinite loop
i += 1;
}
Copy the code
Teacher Zha said: look at the application of loop structure grammar, a few lines of code to solve the original problem. And if you want to change the number of output times, you only need to change the condition part of the loop.
Case Requirement 2: To print 50 papers.
Analysis of ideas:
- This case is a repetitive step requirement, which is solved by a circular control statement
- To apply the while loop, you need to identify the two fixed components of the loop in this case.
- Cyclic conditions:
< = 50
- Cycle operation: print test papers
- Cyclic conditions:
- Write code using the syntax of the while loop
- Check whether it is normal to exit the loop after the service is complete
Code implementation:
// 1. Initialize the loop variable
int i = 1;
// 2. Loop conditions
while (i <= 50) {
// 3
System.out.println("Printing number" + i + "An exam paper");
// 4. Circulation outlet
i += 1;
}
Copy the code
The do while loop
Case requirement: The teacher checks whether the learning task of Xiong Er is qualified every day, if not, he will continue. The teacher arranged the daily learning tasks for Two Xiong: reading textbooks in the morning, learning the theory part, computer programming in the afternoon, master the code part.
This demand can be roughly identified as a cycle to solve the two elements of the cycle:
-
Cyclic conditions: Check unqualified continue
-
Cyclic operation: learning tasks (reading textbooks and learning theories in the morning, programming on the computer and mastering codes in the afternoon)
However, we find that there are significant differences between this case and the previous two cases:
- Logical sequence: Its logic is that the learning task is performed first (loop operations) and then checked by the teacher (loop conditions).
- The condition is complex: its condition is no longer the ordinary number of increasing, but to judge whether qualified.
Faced with this requirement, the conditions are complex enough to change the corresponding variables, but the logical order is not consistent with the flow of a while loop (the while loop performs the judgment first and then the loop operation). Thus, the second loop structure syntax provided by the Java language comes in handy: the do-while loop.
grammar
do{loop body/loop operation}while(cyclic condition);Copy the code
From the flowchart, we can see that the execution of a do-while loop requires a do (loop operation) followed by the execution of the loop condition. And it will loop at least once, whether the condition is true or not.
use
Let’s solve the bear 2 problem using do-while.
Scanner input = new Scanner(System.in);
// 1. Initialize the loop variable
String result;
// use the do-while statement
do {
// 2
System.out.println(Xiong read the textbook and studied the theory part in the morning.);
System.out.println("Bear Tuesday afternoon computer programming, master the code part.");
// 3. Circulation outlet
System.out.print((Y/N) :);
result = input.next();
} while ("n".equals(result)); // 4. Loop conditions
System.out.println("Learn today!");
Copy the code
The for loop
Let me introduce you to the last type of loop: the for loop.
According to?
The for loop is a loop syntax we use a lot later! Why high frequency use, there must be a reason, look at the following “output 100 times, good study” to achieve comparison!
// =============while loop =============
// 1. Initialize the loop variable
int i = 1;
// 2. Loop conditions
while (i <= 100) {
// 3
System.out.println("The first" + i + "Times: good good study, day day up!");
// 4. Circulation outlet
// use the variable I as a loop condition, if the value of I does not change, there will be an infinite loop
i += 1;
}
Copy the code
// =============for loop =============
for (int i = 1; i <= 100; i += 1) {
System.out.println("The first" + i + "Times: good good study, day day up!");
}
Copy the code
Obviously, with a constant number of loops, the for loop is cleaner than the while loop.
grammar
The syntax of the for loop is more concise and flexible, but the four elements of the loop summarized above are unchanged. It just requires us to specify a few components of the loop that are often forgotten so that we can focus more on the loop. So you can think of the for loop as an extension of the while loop. (Just like multiple if extensions select structure for switch)
Teacher Zha said: Personally speaking, IF both for and while can solve the problem, I prefer to use for. Because you write code top-down when you use a while loop, you often forget about the exit of the loop.
forInitialize the loop variable; Cyclic conditions; Circulation outlet) {circulation body/circulation operation}Copy the code
use
Case Requirement 1: Input a student’s final exam scores of 5 courses in a loop and calculate the average score.
Analysis of ideas:
Average score: Total score/quantity
-
This case is a repetitive step requirement, which is solved by a circular control statement
-
Identify the two fixed components of the loop in this case
- Cyclic conditions:
< = 5
- Loop operation: Enter each course score and sum (+=)
- Cyclic conditions:
-
Since it is a fixed-number loop, write code using the syntax of a for loop
- Initialize loop variables: Prepare a start variable for the loop condition expression
- The loop condition
- Cycle operation
- Loop exit: Changes a variable in a loop condition expression so that the loop can end at a specified time
-
Check whether it is normal to exit the loop after the service is complete
Code implementation:
Scanner input = new Scanner(System.in);
System.out.print("Please enter student name:");
String name = input.next();
// Define variables to store scores and
double sum = 0;
// Enter your scores for each course
for (int i = 1; i <= 5; i++) {
System.out.print("Please enter no" + i + "Grade of course:");
double score = input.nextDouble();
// Add the result and
sum += score;
}
// Calculate the average score, which = grades and/number of classes
double avg = sum / 5;
System.out.println(name + The average score of" + avg);
Copy the code
Case requirement 2: Output the addition table as shown.
Analysis of ideas:
-
This case is a repetitive step requirement, which is solved by a circular control statement
-
Identify the two fixed components of the loop in this case
-
Loop condition: <= input value
-
Loop operation: Output addition operation
Two operands of an addition operation
- First operand: increments from 0 to the value you entered
- Second operand: decrement from the value you entered to 0
-
-
Since it is a fixed-number loop, write code using the syntax of a for loop
- Initialize loop variables: Prepare a start variable for the loop condition expression
- The loop condition
- Cycle operation
- Loop exit: Changes a variable in a loop condition expression so that the loop can end at a specified time
-
Check whether it is normal to exit the loop after the service is complete
Code implementation:
Scanner input = new Scanner(System.in);
System.out.print(Please enter a value:);
int num = input.nextInt();
System.out.println("From this value the following addition table can be printed:");
// Use the for syntax
Int I = 0, j = num; This is also the way variables are defined, but not often
for (int i = 0, j = num; i <= num; i++, j--) {
System.out.println(i + "+" + j + "=" + (i + j));
}
Copy the code
Or:
Scanner input = new Scanner(System.in);
System.out.print(Please enter a value:);
int num = input.nextInt();
System.out.println("From this value the following addition table can be printed:");
// Use the for syntax
// Define two calculation variables
int i = 0;
int j = num;
for (; i <= num;) {
System.out.println(i + "+" + j + "=" + (i + j));
// Loop exit
i++;
j--;
}
Copy the code
Matters needing attention
- All three terms of the for loop can be omitted, but two
;
Number can not save! After you omit three items, you have an endless loop. - Initialization variables and loop exits in a for loop can be separated out, for example, to improve the scope of a variable.
- For loops can only be used in scenarios where the number of loops is fixed.
The difference between the three cycles
Difference in execution order:
- While loop: Judge and then execute
- Do-while loop: execute and judge later. The do-while is executed at least once if the initial condition does not satisfy the loop condition.
- For loop: Judge and then execute
Differences in application:
- For loops are usually used when the number of loops is fixed
- While or do-while loops are usually used when the number of loops is uncertain
Infinite loop
Above the introduction of the cycle, Teacher Cha mentioned a lot of a concept: dead cycle. A dead loop is a phenomenon where you can’t end a loop because you have no exit.
The following are the three simplest examples of code that can cause an infinite loop if a loop condition or loop exit is wrong or missing.
while (true) {}Copy the code
do{}while (true);
Copy the code
for(;;) {}Copy the code
In theory, it is a bad situation to have an endless cycle, but as the saying goes, “There is no good or evil in gongfu. It depends on the user. “Using dead loops properly will make your programming easier.
For example, using an infinite loop is more appropriate when you don’t know when a loop will end. But it is usually used in conjunction with jump statements.
Jump statements
break
Take part in long-distance race in life, if in the process of the race is not up/discomfort, you can quit the race.
In the program, there is also the need to not execute the loop under specified circumstances, at this time jump statements can flexibly schedule the loop process.
The break keyword, as seen in the switch statement, means to break. It can also be used in three loop structures where it terminates the current loop and jumps to the next statement outside the loop block.
// Pseudo code: 4000 meters
for (int i = 0; i < 10; i++) {
if(physical exhaustion) {// Exit the contest
break; }}Copy the code
Case requirements: input the scores of a student’s 5 courses in a cycle and calculate the average score. If a score is negative, stop the input and prompt the input error.
This requirement, just like the one implemented in the for loop, is just a little bit of an added requirement.
Scanner input = new Scanner(System.in);
System.out.print("Please enter student name:");
String name = input.next();
double sum = 0;
// elevate the scope
// If I is defined in a for block, it can only be used in a for block.
int i = 1;
for (; i <= 5; i++) {
System.out.print("Please enter no" + i + "Grade of course:");
double score = input.nextDouble();
// If a negative number is entered, an error is displayed and the loop ends
if (score < 0) {
System.out.println("Wrong score entry! Please start typing again!");
break;
}
sum += score;
}
// End the loop early without averaging the score
if (i > 5) {
double avg = sum / 5;
System.out.println(name + The average score of" + avg);
}
Copy the code
continue
In addition to break, there is a jump statement: continue. As the name implies, it is used to skip the remaining statements in the loop body and immediately perform the next loop condition judgment, which can be understood as only ending the loop.
Case requirements: Use the loop + continue implementation to input the scores of students in Java class, and count the proportion of students with scores greater than or equal to 80 points.
Scanner input = new Scanner(System.in);
System.out.print("Please enter total class size:");
int num = input.nextInt();
// Set the number of students with >= 80 points
int count = 0;
for (int i = 1; i <= num; i++) {
System.out.print("Please enter no" + i + A student's score:);
double score = input.nextDouble();
// Count the number of students whose scores >= 80 or above
if (score < 80) {
// End this loop and enter the next loop
continue;
}
// Add up the number of people
count ++;
}
/ / calculate
double percent = count * 1.0 / num * 100;
System.out.println("The number of students with more than 80 points is:" + count);
System.out.println("The proportion of students with 80 or more is:" + percent + "%");
Copy the code
Teacher Zha said: “Continue is not necessary for this case. We can also change part of the code of statistics to:
if (score > 80) { count ++; } Copy the code
An infinite loop + jump statement
Ok, and then introduce the jump statement, teacher cha to introduce a dead loop combined with the jump statement, the application of repeated input.
- The use of an infinite loop allows the program to continue forever
- The break is used to end the loop
- Continue is used to end the loop and enter the next loop
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please enter user name:");
String username = input.next();
System.out.print("Please enter user password:");
String password = input.next();
// Fail to lose again
if(! ("admin".equals(username)
&& "abcd123".equals(password))) {
System.out.println("Login failed! Please re-enter!");
// End the loop and enter the next loop
continue;
}
// End the loop
break;
}
System.out.println("Login successful!");
Copy the code
Teacher Zha said: do you feel a little burned brain? Just write it a few more times! It could also be written down here.
However, Teacher Zha personally prefers the writing method of death cycle. As long as the “time” comes, it can end or enter the next one at any time. It is very direct, very pure and very decisive.
Scanner input = new Scanner(System.in); boolean flag; do { // Initialize the loop variable // The initial value is true, and the flag status is changed to false only when the login succeeds to end the loop flag = true; System.out.print("Please enter user name:"); String username = input.next(); System.out.print("Please enter user password:"); String password = input.next(); // Fail to lose again if ("admin".equals(username) && "abcd123".equals(password)) { System.out.println("Login successful!"); // Change the loop state flag = false; } else { System.out.println("Login failed! Please re-enter!"); }}while (flag); Copy the code
reference
[1] Zhang Guizhu, Zhang Ping, Chen Aiguo. Java Object-oriented Programming (JDK1.6) 3rd edition: Beijing University of Posts and Telecommunications Press, 2005
Afterword.
Ok, the introduction of the loop structure is over here, this homework please search wechat attention: look up the teacher’s handout, and then reply to the loop structure homework.
I think you’re going to start having a little headache after this. Because of the loop it starts to get a little abstract, a few simple lines of code can represent hundreds of operations, and the more complex the loop, the more spatial thinking is required, but don’t worry, in the next article, Mr. Chu saves you.
In addition, Teacher Zha gives different solutions to the same needs repeatedly in this paper, which will be uncomfortable for the first time learning and “stereotyped” learning students, because they do not know which to choose.
But in fact, life is never a “stereotyped” step, the problems encountered in life are not always “stereotyped” to solve, the program is the same, thousands of people, thousands of questions, thousands of solutions.
Here’s a tip for you: Choose a favorite solution based on your situation. Then, when that solution fails to solve the problem, consider another solution or more.
Teacher Zha said: For the learning of technology, teacher Zha has always followed the following steps: With a simple demo to let it run first, and then learn it the most commonly used API and configuration can let yourself up, finally, on the basis of proficiency in the spare time reading the source to try to make myself to be able to see clearly its running mechanism, part of the cause of the problem, at the same time, draw lessons from these technology to enhance your own code level.
So in the teacher’s article, the early basic are small white, only interspersed with a very small amount of source research. Of course, such as the small white update, you still like, the late will not regularly dedicated to part of the technology of the source code analysis.