"Java from small white to Daniel" The 7th chapter control statements

Source: Internet
Author: User
Tags case statement terminates

"Java from small white to Daniel" paper version has been shelves!!!

There are three kinds of control statements in program design, namely, order, branch and Loop statement. The Java program manages the flow of the program through control statements to accomplish certain tasks. A program flow consists of several statements that can be a single statement or a compound statement enclosed in curly braces ({}). Control statements in Java are available in the following categories:

    • Branching statements: if and switch.
    • Looping statements: While, Do-while, and for
    • Jump statements: Break, continue, return, and throw
7.1 Branch Statements

Branching statements provide a control mechanism that allows the program to "judge the ability" to analyze problems like human brains. A branch statement is also called a conditional statement, which enables some programs to be selectively executed based on the values of certain expressions. The Java programming language provides both if and switch two branch statements.

7.1.1 If statement

The choice structure guided by the IF statement has the IF structure, the IF-ELSE structure and the ELSE-IF structure three kinds.

# # # #1. If structure

If the conditional expression is true, the statement group is executed, otherwise the statement after the if structure is executed. If the statement group has only one statement, you can omit the curly braces, and when you do not omit the curly braces from the programming specification angle, the omission of the curly braces is a poor readability of the program. The syntax structure is as follows:

if (条件表达式) {   语句组}

The example code for the If structure is as follows:

int score = 95;if (score >= 85) {    System.out.println("您真优秀!");}if (score < 60) {    System.out.println("您需要加倍努力!");}if ((score >= 60) && (score < 85)) {    System.out.println("您的成绩还可以,仍需继续努力!");}

The results of the program run as follows:

您真优秀!

# # # #2. If-else structure

All languages have this structure, and the format of the structure is basically the same, the statement is as follows:

if (条件表达式) {   语句组1 } else {   语句组2 }

When the program executes to the IF statement, the conditional expression is evaluated first, if the value is true, the statement group 1 is executed, then the ELSE statement and statement Group 2 are skipped, and the following statement continues. If the value of the conditional expression is false, the statement group 1 is ignored and the statement set 2 is executed, and then the following statement continues.

The sample code for the IF-ELSE structure is as follows:

int score = 95;if (score < 60) {    System.out.println("不及格");} else {    System.out.println("及格");}

The results of the program run as follows:

及格

# # # #3. ELSE-IF structure

The ELSE-IF structure is as follows:

if (条件表达式1) {    语句组1 } else if (条件表达式2) {    语句组2} else if (条件表达式3) {    语句组3 ... } else if (条件表达式n) {    语句组n} else {    语句组n+1}

As you can see, the ELSE-IF structure is actually a multi-layered nesting of the if-else structure, and its obvious feature is that only one group of statements is executed in multiple branches, and none of the other branches are executed, so this structure can be used in a branch with multiple judgment results.

The sample code for the ELSE-IF structure is as follows:

int testScore = 76;char grade;if (testScore >= 90) {    grade = ‘A‘;} else if (testScore >= 80) {    grade = ‘B‘;} else if (testScore >= 70) {    grade = ‘C‘;} else if (testScore >= 60) {    grade = ‘D‘;} else {    grade = ‘F‘;}System.out.println("Grade = " + grade);

The output results are as follows:

Grade = C

Where char grade is the declaration of a character variable, and then the final result is determined to be c.

7.1.2 Switch statement

Switch provides a multi-branch program Structure statement. Here's a look at the syntax structure of the basic form of the switch statement, as follows:

switch (表达式) {     case 值1:        语句组1     case 值2:        语句组2     case 值3:        语句组3             ...     case 判断值n:        语句组n     default:        语句组n+1 }

The expression in the switch statement evaluates to only int, Byte, short, and char types, and cannot be a long or other type. Each case can be followed only by a constant of type int, Byte, short, and char, and the default statement can be omitted.

When the program executes to the switch statement, the value of the conditional expression is evaluated first, the value is a, then a is matched with the value 1 in the 1th case statement, if the match executes statement Group 1, and the statement group executes without jumping out of switch, only the break is encountered to jump out of switch. If a does not match the 1th case statement, the 2nd Case statement is matched, if the match executes statement Group 2, and so on, until statement group N is executed. If all of the case statements are not executed, the default statement group N+1 is executed, and then the switch is not jumped out.

The sample code is as follows:

int testScore = 75;char grade;switch (testScore / 10) {           ①case 9:    grade = ‘优‘;    break;case 8:    grade = ‘良‘;    break;case 7:          // 7是贯通的       ②case 6:    grade = ‘中‘;    break;default:    grade = ‘差‘;}System.out.println("Grade = " + grade);

The output results are as follows:

Grade = 中

The above code to convert 100 points to: "Excellent", "good", "medium", "poor" scoring system, of which 7 points and 6 points are "middle" results, case 7 and cases 6 as a situation to consider. The Code section ① evaluates the expression to get the 0~9 fractional value. Case 7 of the code line ② is connected, without break after the program flow executes the current case, the next case is entered, so both case 7 and case 6 are executed in the same code.

7.2 Loop Statements

The Loop statement enables the program code to execute repeatedly. Java supports three types of looping constructs: while, Do-while, and for. The for and while loops test the loop condition before the loop body is executed, and do-while tests the loop condition after the loop body is executed. This means that the for and while loops may not even be executed once for the loop body, and Do-while will execute at least one loop body at a time. In addition Java 5 after the introduction of the For-each Loop statement, For-each Loop is the transformation for the loop, it is specifically designed for the collection traversal, note that For-each is not a keyword.

7.2.1 While statement

The while statement is a loop structure that is judged first, in the following format:

while (循环条件) {    语句组}

While Loop has no initialization statement, the number of cycles is not known, as long as the loop condition is satisfied, the loop will go on.

Let's look at a simple example with the following code:

int i = 0;while (i * i < 100000) {    i++;}System.out.println("i = " + i);System.out.println("i * i = " + (i * i));

The output results are as follows:

i = 317i * i = 100489

The purpose of the above program code is to find the largest integer with a square number less than 100000. There are a few points to note when using a while loop, while a while looping condition statement can only write an expression and is a Boolean expression, so if a loop variable is required in the loop body, the loop variable must be initialized before the while statement. In this example, I is assigned a value of 0, and then inside the loop body must change the value of the loop variable through the statement, otherwise a dead loop will occur.

7.2.2 do-while Statements

The use of the Do-while statement is similar to the while statement, although the Do-while statement is a cyclic conditional structure, with the following statement format:

do {  语句组} while (循环条件)

Do-while Loop has no initialization statement, the number of cycles is not known, regardless of whether the loop condition is satisfied, will first execute a loop body, and then judge the loop condition. If the condition is satisfied, the loop body is executed and the loop is stopped if it is not satisfied.

Let's look at a sample code:

int i = 0;do {    i++;} while (i * i < 100000);System.out.println("i = " + i);System.out.println("i * i = " + (i * i));

The output results are as follows:

i = 317i * i = 100489

This example is the same as the example in the previous section, where the largest integer with a square number less than 100000 is found. The output is the same.

7.2.3 for statement

The For statement is the most widely used and most powerful loop statement. The general format is as follows:

for (初始化; 循环条件; 迭代) {  语句组}

The For statement executes process 7-1, which first executes the initialization statement, which initializes the loop variable and other variables, and then the program determines whether the loop condition is satisfied and, if so, resumes execution of the loop body and computes the iteration statement before judging the loop condition, so repeated, Jumps out of the loop until the loop condition is judged to be unsatisfied.

The following sample code is a square table program that calculates 1~9:

System.out.println("---------");for (int i = 1; i < 10; i++)  {    System.out.printf("%d x %d = %d", i, i, i * i);    //打印一个换行符,实现换行    System.out.println();}

The output results are as follows:

---------1 x 1 = 12 x 2 = 43 x 3 = 94 x 4 = 165 x 5 = 256 x 6 = 367 x 7 = 498 x 8 = 649 x 9 = 81

At the beginning of the loop part of this program, the loop variable i is assigned a value of 1, each cycle to determine whether the value of I is less than 10, if true, then the loop body is executed, then I plus 1. Therefore, the final result is to print out the square of the 1~9, excluding 10.

Tip initialization, looping conditions, and iterations can all be empty statements (but semicolons cannot be omitted), while all three are empty, equivalent to an infinite loop. The code is as follows: *

for (; ;) {    ...}

In addition, in the initialization and iteration sections, you can use a comma statement to perform multiple operations. The comma statement is a comma-delimited sequence of statements, as shown in the following program code:

int x;int y;for (x = 0, y = 10; x < y; x++, y--) {    System.out.printf("(x,y) = (%d, %d)", x, y);    // 打印一个换行符,实现换行    System.out.println();}

The output results are as follows:

(x,y) = (0,10)(x,y) = (1,9)(x,y) = (2,8)(x,y) = (3,7)(x,y) = (4,6)
7.2.4 For-each Statements

After Java 5, A For loop--for-each loop dedicated to iterating through the collection is provided. Using the For-each loop does not have to write code according to the standard routines of for, it is only necessary to provide a collection to traverse.

Suppose you have an array that iterates through an array with a for statement as follows:

// 声明并初始化int数组int[] numbers = { 43, 32, 53, 54, 75, 7, 10 };System.out.println("----for-------");// for语句for (int i = 0; i < numbers.length; i++) {    System.out.println("Count is:" + numbers[i]);}

The above statement int[] numbers = {43, 32, 53, 54, 75, 7, 10} declares and initializes a collection of 10 element arrays, so now all you need to know is that when initializing an array, put elements of the same type into {...} and separated by commas (,), the collection of arrays is described in detail in the following 8th chapter. Numbers.length is the length of the obtained array, and length is the property of the array, and Numbers[i] is the array element that is accessed by an array subscript.

The way to iterate through an array with the For-each Loop statement is as follows:

// 声明并初始化int数组int[] numbers = { 43, 32, 53, 54, 75, 7, 10 };System.out.println("----for each----");// for-each语句for (int item : numbers) {    System.out.println("Count is:" + item);}

As you can see from the example, item is not a looping variable, it holds the elements in the collection, the For-each statement takes the element one by one out of the collection, and saves it to item, which does not need to use the loop variable to access the elements in the array through an array subscript. Visible For-each statements are much simpler and easier to iterate through the collection.

7.3 Jump Statements

Jump statements can change the order of execution of the program, which allows the program to jump. There are 4 types of jump statements in Java: Break, continue, throw, and return. This chapter focuses on the use of break and continue statements. Throw and return are described in the following sections.

7.3.1 Break statement

The break statement can be used for the while, Repeat-while, and for loop structure described in the previous section, which is forced to exit the loop body and no longer executes the remaining statements in the loop body.

There are two ways to use break statements in a loop body: with labels and without labels. The syntax format is as follows:

break; //不带标签break label; //带标签,label是标签名

A break statement without a label causes the program to jump out of the loop body of the layer, while a tagged break statement causes the program to jump out of the loop body indicated by the label.

Here is an example of the following code:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };for (int i = 0; i < numbers.length; i++) {    if (i == 3) {        //跳出循环        break;    }    System.out.println("Count is: " + i);}

In the above program code, when the condition I==3 executes the break statement, the break statement terminates the loop, and the results of the program run are as follows:

Count is: 0Count is: 1Count is: 2

Break can also be used with tags, as shown in the example code:

label1: for (int x = 0; x < 5; x++) {           ①    for (int y = 5; y > 0; y--) {               ②        if (y == x) {            //跳转到label1指向的循环            break label1;               ③        }        System.out.printf("(x,y) = (%d,%d)", x, y);        // 打印一个换行符,实现换行        System.out.println();    }}System.out.println("Game Over!");

By default, break only jumps out of the nearest inner loop (code ② line for loop). If you want to jump out of the outer loop of the ① line of code, you can add a label label1 to the outer loop, and notice that the label is defined with a colon followed by it. The Label1 tag is specified after the break statement in line ③, so that when the condition satisfies the execution of the break statement, the program jumps out of the loop specified by the Label1 label.

The results of the program run as follows:

(x,y) = (0,5)(x,y) = (0,4)(x,y) = (0,3)(x,y) = (0,2)(x,y) = (0,1)(x,y) = (1,5)(x,y) = (1,4)(x,y) = (1,3)(x,y) = (1,2)Game Over!

If no outer loop label is specified after break, the result is as follows:

(x,y) = (0,5)(x,y) = (0,4)(x,y) = (0,3)(x,y) = (0,2)(x,y) = (0,1)(x,y) = (1,5)(x,y) = (1,4)(x,y) = (1,3)(x,y) = (1,2)(x,y) = (2,5)(x,y) = (2,4)(x,y) = (2,3)(x,y) = (3,5)(x,y) = (3,4)(x,y) = (4,5)Game Over!

Comparing the two running results, you will find the meaning of adding tags to break, it is necessary to add tags for multi-layer nested loops, and proper use can improve the execution efficiency of the program.

7.3.2 Continue statements

The continue statement is used to end the loop, skipping statements that have not yet been executed in the loop body, and then judging the termination condition to determine whether to continue the loop. For a For statement, the iteration statement is executed before the termination condition is judged.

There are two ways to use the Continue statement in the loop body, either with a label or without a label. The syntax format is as follows:

continue //不带标签continue label //带标签,label是标签名

Here is an example of the following code:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };for (int i = 0; i < numbers.length; i++) {    if (i == 3) {        continue;    }    System.out.println("Count is: " + i);}

In the above program code, when the condition I==3 executes the Continue statement, the continue statement terminates the loop, the statement after continue in the loop body is no longer executed, and then the next loop, so there is no 3 in the output result. The results of the program run as follows:

Count is: 0Count is: 1Count is: 2Count is: 4Count is: 5Count is: 6Count is: 7Count is: 8Count is: 9

The sample code for the tagged continue statement is as follows:

label1: for (int x = 0; x < 5; x++) {       ①    for (int y = 5; y > 0; y--) {       ②        if (y == x) {            continue label1;        ③        }        System.out.printf("(x,y) = (%d,%d)", x, y);        System.out.println();    }}System.out.println("Game Over!");

By default, continue only jumps out of the nearest inner loop (code ② line for loop), and if you want to jump out of the outer loop of the ① line of code, you can add a label label1 to the outer loop, and then specify the label ③ after the continue statement on the Label1 line. This way, when the condition satisfies the execution continue statement, the program jumps out of the loop.

The results of the program run as follows:

(x,y) = (0,5)(x,y) = (0,4)(x,y) = (0,3)(x,y) = (0,2)(x,y) = (0,1)(x,y) = (1,5)(x,y) = (1,4)(x,y) = (1,3)(x,y) = (1,2)(x,y) = (2,5)(x,y) = (2,4)(x,y) = (2,3)(x,y) = (3,5)(x,y) = (3,4)(x,y) = (4,5)Game Over!

because x = = Y is skipped, the following content is not output.

Summary of this chapter

By learning about the content of this chapter, the reader can learn about the control statements of the Java language, including branch statements (if and switch), looping statements (while, Do-while, for, and For-each), and jump statements (break and Continue).

Companion video

Http://edu.51cto.com/topic/1507.html

Supporting source code

Http://www.zhijieketang.com/group/5

and the free version of this book corresponds to a fee version:
    1. Enter Baidu to read ebook

    2. Access to Turing Community ebook

"Java from small white to Daniel" The 7th chapter control statements

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.