Java entry tutorial: Chapter 4 flow control

zhaozj2021-02-16  88

With C, C , Java procedure is transfers the process stream to complete a set of tasks. The program stream is composed of a dry statement. The statement can be a single statement (such as c = a b;), it can also be a complex statement enclosed in bulk {}. Let's introduce the stream control statement in Java, including 1. Branch statement: IF-else, break, switch, return. 2. Cycle statement: While, Do-while, for, contract, 3. Exception Processing statement: TRY -catch-finally, throw finally introduces the comment statement. § 4.1 Sub-assault sentences provide a control mechanism that enables the program's execution to skip some statements, do not execute, and turn to the specific statement. 4.1.1 Conditional Statement If-else. If the IF-ELSE statement performs one of two operations according to the true hypothesis of the determination condition, its format is: if (boolean-expression) statement1; [else Statement2;] 1. Boole Expression Boolean-Expression is any expression that returns Boolean data (this is strict than C, C limit). 2. Everyone must have a number after each single statement. 3. It is also enclosed in a single statement, which is enclosed in a single statement, and the program is highly readable, and it is conducive to pruning (can fill in new statements). Outside the outer surface is not equipped. The 4.ELSE clause is optional. 5. If the value of the Bull Test is True, the program is executed in STATEMENT1, otherwise it executes ST ATEMENT2. 6. A special form of IF-ELSE statement: if (expression1) {statement1} else if (expression2) {statement2} ...} else if (expressionm) {statementm} else {statementn} @@@ [else clause It cannot be used separately as a statement, it must be used with the IF. Else always pairs it closest to it. Parallel relationships can be changed by using braces {}. 7. Example: Example 4.1 Compares two numbers of size and outputs from small to large order. @@@ [public class comparetwo {public static void main (string args []) {double d1 = 23.4; double d2 = 35.1; if (d2> = d1) System.out.println (D2 "> =" D1) Else System.Out.println (D1 "> =" D2);}} Run results are: C: /> Java Comparetwo 35.1> = 23.4 Example 4.2 Declaration is a leap year in a year. The conditions of the leap year are one of the two sides: 1 can be 4 consolidation, but cannot be removed by 10 0; 2 can be divided by 4, and can be 100

Public class leafyear {public static void main (string args []) {int year = 1989; // method 1 IF ((Year% 4 == 0 && year% 100! = 0) || (Year% 400 == 0 )) System.out.Println (Year "is a leap year."); Else System.Out.println (Year "is not a leap year."); Year = 2000; // method 2 Boolean Leap; if (Year % 4! = 0) Leap = false; Else IF (Year% 100! = 0) Leap = true; Else IF (Year% 400! = 0) Leap = false; else leap = true; if (Leap == True) System.out.println (Year "Is A Leap Year."); Else System.Out.println (Year "Is Not a Leap Year."); Year = 2050; //Method3 IF (Year% 4 == 0) {IF (Year% 100 == 0) {IF (Year% 400 == 0) Leap = true; else leap = false;} else leap = false;} else leap = false; if (leap == true) system. Out.println (Year "Is A Leap Year."); Else System.Out.println (Year "Is Not a Leap Year.");}} The result is C: /> Java Leepyear 1989 is not a leap year. In this example, method 1 contains all leap year conditions with a logical expression, method 2 uses a special form of the IF-ELSE statement, and method 3 is by using braces. {} Matches if-else to implement the judge of the leap year. The big home can be based on the procedure, and the groups and districts in which the body will be used in the case, and the method is used in the same way. 4.1.2 Multi-Branch Statement Switch Switch Statement Performs one of multiple operations based on the value of the expression, its general format is as follows: Switch (expression) {case value1: statement1; break; case value2: statement2; break; ...... ... Case Valuen: statemendn; break; [default: defaultStatement ";]} 1. Expression Expression can return any simple type of value (such as integer, real, character type), multi-branch statement returned to the value Compared to the values ​​in each CASE clause. If you match the function, you will perform the statement sequence after the Case clause.

2. The value of the value in the Case clause must be a constant, and the value in all CASE clauses should be different. 3. DEFAULT clause is optional. When the value of the table is not matched with the value in any CASE clause, the program is executed in the statement of the DEFAULT. If the value of the table, the value in any case clause does not match the value and there is no DEFAULT clause, and the program does not do anything, but directly jumps out the Switch statement. 4. BREAK statement is used to make a Switch statement after being punched in a CASE, that is, the execution of the Switch statement. Because the CASE clause only acts as a label, it is used to find the matching entry and start executing from which it will not match the rear case clause, but directly execute the subsequent statement sequence, therefore should be at each After the CASE branch, use Break to terminate the execution of the rear CASE branch statement. In some special circumstances, multiple different case values ​​should be implemented in a group of work, which is not available without BREAK. 5 enclose. 6. Switch statement can be implemented with IF-Else, but in some cases, use the Switch statement smallerly, the readability is strong, and the execution rate of the program is increased. 7. Example: Example 4.3. Prints the 100-point score segment according to the level of test results.

Public class gradelevel {public static void main (string args []) {system.out.println ("/ n ** first situation **); char grade = 'c'; // Normal Use switch (grade) {casse 'A': System.Out.println (Grade "IS 85 ~ 100"); Break; Case 'B': System.out.Println (Grade "IS 70 ~ 84"); Break; Case 'C': System. Out.println (Grade "IS 60 ~ 69"); Break; Case 'D': System.out.Println (Grade "IS <60"); Break; Default: System.out.println ("Input Error"); } System.out.println ("/ n ** second situation **); grade = 'a'; ∥Creat Error WITHOUT BREAK STATEMENT SWITCH (GRADE) {CASE 'A': System.out.Println (Grade " IS 85 ~ 100 "); case 'b': system.out.println (Grade " IS 70 ~ 84 "); Case 'C': System.out.Println (Grade " IS 60 ~ 69 "); Case 'D' : System.out.Println (Grade "IS <60"); default: system.out.println ("Input Error");} system.out.println ("/ n ** third situation **); grade = 'B'; ∥several case with same operation switch (grade) {case 'a': case 'b': case 'c': system.out.println (Grade "IS> = 60"); Break; Case 'D ': System.ou T.Println (Grade "IS <60"); Break; default: system.out.println ("Input Error");}}} Run result is C: /> java gradeelevel **** first situation **** C IS 60 ~ 69 **** Second Situation **** a IS 85 ~ 100 A IS 70 ~ 84 A IS 60 ~ 69 A IS <60 Input Error **** Third Situation **** B IS> = 60 From this example we can see the role of the BREAK statement.

4.1.3 BREAK statement 1. In the Switch language, the BREAK statement is used to end the Switch statement. Enable the program to start executing from the first statement after the Switch statement. 2 The resulting code. The format of the scales is as follows: BlockLabel: {codeblock} The second way to jump out of the blocks it specifically, and is tight with the first statement of the block. The format is: Break BlockLabel, for example: A: {... // tag code block AB: {... // Tag code block BC: {... // Tag code block C Break B; ... // Will Not Be Executed} ... // Will Not Be Executed} ...... / execute from here} 3. Unlike C, C , there is no goto statement in Java to achieve any jump, because the G OTO statement destroys the readability of the program, and Effect of optimization of compilation. However, from the above example, Java uses Break to realize some of the advantages of the GOTO statement. If the flag specified after Break is not the sign number of a code block, but a statement, this time BREAK is fully realistic. It should not be used to avoid this method.  (untrained Sentence) 4.1.4 Return Strategy Return Return Retur Natives From the front method, returning to the statement of the call to the method, and follow the next statement of the statement. (With the contents of the Guan method, we will tell the details in Chapter 6. Main () in the front case is a method). There are two formats that return the statement: 1. Return Expression returns a value to the statement of the method, the data type of the return value must be in a return value type in the form of the method. It can be used to make the type of type. 2.Return When the method is said to use the VOID sound to return to the type, it should be used in this format, it does not return any value. Return statement is commonly used in the first place to withstand the method and return a value. In Java, a single RETURN statement is used in the middle of a manner, and it will produce a compilation error, because there will be some statements that do not have a statement. However, by embedning the return statement into some statements (such as if-else), exiting the program when all statements in the finished method are exited, for example: int method (int num) {∥ Return Num; ∥Will Cause Compile Time Error IF (Num> 0) Return Num; ...... ∥ May or May Not Be Executed ∥Depending on the value of num § 4.2 The role of the loop statement cycle statement is repeatedly executed, until the condition of the termination cycle is met, a loop is generally It should include four sections: 1. Initialization: Some of the initial conditions used to set the loop, such as the counter cleaner.

2. Circulation Body Score: This is a code of the reverse cycle, which can be a single statement, or a complex statement. 3. Iteration: This is in the front cycle end, the next cycle starts before the statement, often used to add 1 or minus the counter 1 or 1. 4. Termination: Tong is often a Bur-formal, and each cycle must be evaluated to the table to verify that the cycle will end conditions. The loop statement provided in Java has: While statement, do-while statement and FOR statement, the next part is done. 4.2.1While Statement While Statement Implements "When" Cycle, its general format is; [ITIZATION] while (Termination) {body; [iphization;]} 1. When the value of the Boolean expression is True, cycle Perform statements in braces. And the initialization part and the iterative part are optional. 2.WHILE statement first calculates the final condition. When the condition is full, the statement in the cycle. This is the feature of the "model" cycle. 4.2.2 DO-WHILE statement do-while statement implements the "until" loop, its general format is: [ITeration;]} while (Termination); 1.DO-while statement first execute loops Body, then calculate the termination condition. If the result is true, the statement in the brak is circulated until the result of the Boolean expression is false. 2. Divoidation with the While, the loop of the Do-While statement is at least once, which is the characteristics of the "until" cycle. 4.2.3 For statement for statement is also used to implement "model" loop, its general format is: for (Initialization; Termination; ITERATION) {body;} 1.For statement is executed, first perform initialization operation, then determine the termination Whether the condition is met, if satisfied, the statement in the cyclic body is performed, and finally the iterative portion is executed. After completing a cycle, we will repeat the final conditions. 2. A variable can be spoken in the initialization portion of the FOR statement, and its work domain is the entire FOR statement. 3.For statement is commonly used to execute the situation determined by the cycle (such as the array element to operate), or the number of uncertainties in the cycle of cycle end strips. 4. In the initialization part and the iterative part can be used to use a comma statement to enter multiple operations. The comma statement is a teas separated statement sequence. For example: for (i = 0, j = 10; i

4.2.4 Continue statement 1.Continue statement is used to end the cycle, skip the statement of the lower surface in the loop, and then the judgment of the end conditions, so that it will continue to cycle. For the FOR statement, the judgment statement must be performed before the judgment of the final conditions. Its format is: Continue; 2. You can also use the Continue to jump to the outer loop indicated by the parentheses, at this time is Continue OuterLable; for example: Outer: for (int i = 0; i <10; i ) { ∥ outer cycle for (int J = 0; j <20; j ) {∥ inner circulation IF (j> i) {... Continue Outer;} ...} ...} In this case, when J> i When the condition performs the corresponding statement, you jump to the outer cycle, perform the iterative statement i of the outer loop; then start the next loop. 4.2.5 Example 4.4 Six cases use while, do-while and eff statement. Public class sum {public static void main (string args []) {system.out.println ("/ n ** while stat **"); int N = 10, sum = 0; ∥initialization while (n> 0) {∥Termination SUM = N; ∥body n--; ∥iteration} system.out.println ("SUM IS" SUM); System.out.Println ("/ N ** do_While Statement **); n = 0; ∥ initialization sum = 0; do {SUM = N; ∥body n ; ∥Teration} while (n <= 10); ∥Termination system.out.println ("SUM IS" SUM); System.out.Println ("/ n ** for statement **); sum = 0; for (int i = 1; i <= 10; i ) {∥initialization, termination, orthoteration sum = i;} system.out.println (" SUM is " sum);}} Run results are: c: /> java sum ** while statement ** SUM IS 55 ** do_WHILE Statement ** SUM IS 55 ** for Statement ** SUM IS 55 can be compared These three loop statements are thereby selecting a suitable statement at different occasions.

转载请注明原文地址:https://www.9cbs.com/read-14016.html

New Post(0)