(translation) Second Language Foundation (4)--Control flow statement

Source: Internet
Author: User
Tags terminates

Control flow Statements

The statements in the code are usually executed from the top down order. But the control flow statement interrupts the execution of the process, taking advantage of decisions, loops, branching, and letting your program conditionally execute some part of the code. This section describes Java-supported decision statements (IF-THEN,IF-THEN-ELSE,SWITCH), loop statements (for,while,do-while), and branch statements (Break,continue,return).

If-then and If-then-else statements

If-then is the most basic of the control flow statements. It tells your program to execute a piece of code when a particular condition is true. For example, the bicycle class would allow the brakes to reduce the speed of the bike, only if the bike is still in motion. The possible implementations of the Applybrakes method are as follows:

void Applybrakes () {

if (ismoving) {

currentspeed--;

}

}

If the condition is false (the bike does not move), skip the If-then statement.

In addition, if there is only one statement, the curly braces are optional.

void Applybrakes () {

if (ismoving)

currentspeed--;

}

Whether to omit curly braces according to personal style. But omitting curly braces makes the code more brittle. If you add statements later in the then branch, a common mistake is to forget to add the corresponding curly braces. The compiler cannot find such errors, so you will get an incorrect result.

The If-then-else statement provides an additional path to execute, when the result of the IF clause is false. You can use the If-then-else statement in the Applybrakes method to perform some actions if the bike uses brakes when it is not in motion. In this example, some error messages will be printed stating that the bike has stopped.

void Applybrakes () {

if (ismoving) {

currentspeed--;

}else{

System.err.println ("Bicycle has already stopped.");

}

}

The following program, according to the score distribution level, greater than 90 is a, greater than 80 is B, greater than 70 is C, greater than 60 is D, the other is F.

Class ifelsedemo{

public static void Main (string[] args) {

int testscore = 79;

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 is" + grade);

}

}

The output is C.

You may notice that the value of testscore satisfies more than one expression in a mixed statement: 79>70;79>60. But when a condition is met, the corresponding statement executes (grade = ' C '), and the remaining conditional statement is not executed.

Switch statement

Unlike the If-then and IF-THEN-ELSE statements, a switch statement can have many paths that can be executed. Switch and byte, short, int, char basic data types work. It can also work with enumeration types, string classes, and some specialized classes that encapsulate the underlying data types: Character, Byte, short, and integer.

The following code declares an int variable month whose value represents the month, and then prints the month according to the Swich statement.

public class switchdemo{

public static void Main (string[] args) {

int month = 8;

String Monthstr;

Switch (month) {

Case 1:MONTHSTR = "January";

Break

Case 2:MONTHSTR = "February";

Break

Case 3:MONTHSTR = "March";

Break

Case 4:monthstr = "April";

Break

Case 5:MONTHSTR = "may";

Break

Case 6:monthstr = "June";

Break

Case 7:MONTHSTR = "July";

Break

Case 8:MONTHSTR = "August";

Break

Case 9:MONTHSTR = "September";

Break

Case 10:MONTHSTR = "October";

Break

Case 11:MONTHSTR = "November";

Break

Case 12:MONTHSTR = "December";

Break

DEFAULT:MONTHSTR = "Invalid month";

Break

}

System.out.println (MONTHSTR);

}

}

The output is August.

The switch statement body is called a switch block. A switch block can have more than one case tag and one statement of the default tag. The switch statement evaluates the expression and executes all statements following the corresponding case tag.

You can also use If-then-else to complete the above code.

int month = 8;

if (month = = 1) {

System.out.println ("January");

}else if (month = = 2) {

System.out.println ("February");

}...

Decide whether to use a switch statement or a IF-THEN-ELSE statement based on the readability of the Code and the statement to be tested. The If-then-else statement can test the range or condition of a value, whereas a switch statement can only test an expression based on an integer, an enumeration value, or a string object.

Another interesting place is the break statement. Each break statement terminates a switch block. The control flow continues to execute the first statement following the switch block. The break statements are required, and if they are not, the statements in the switch block are executed throughout: All statements following the match case tag are executed sequentially, regardless of whether the value of the following case matches until the break statement is encountered. The following code shows that the switch block is executed from top to bottom, and calculates month of month and all subsequent months of the year.

Class switchfallthroughdemo{

public static void Main (string[] args) {

java.util.arraylist<string> futuremonths = new java.util.arraylist<string> ();

int month = 8;

Switch (month) {

Case 1:futuremonths.add ("January");

Case 2:futuremonths.add ("February");

Case 3:futuremonths.add ("March");

Case 4:futuremonths.add ("April");

Case 5:futuremonths.add ("may");

Case 6:futuremonths.add ("June");

Case 7:futuremonths.add ("July");

Case 8:futuremonths.add ("August");

Case 9:futuremonths.add ("September");

Case 10:futuremonths.add ("October");

Case 11:futuremonths.add ("November");

Case 12:futuremonths.add ("December");

Break

Default:break;

}

if (Futuremonths.isempty ()) {

System.out.println ("Invalid month number");

}else{

for (String month:futuremonths) {

System.out.print (month+ "");

}

}

}

}

Output: August September October November December

Technically, the last break statement is not required because the process has flowed out of the switch statement. It is recommended to use break to easily modify code and reduce the likelihood of errors. The default code snippet handles all values that are not processed by the case code snippet.

The following example shows that a statement has multiple case labels. This example calculates the number of days in a month.

Class switchdemo2{

public static void Main (string[] args) {

int month = 2;

int year = 2000;

int numdays = 0;

Switch (month) {

Case 1:caes 3:case 5:case 7:case 8:case 10:case 12:

Numdays = 31;

Break

Case 4:case 6:case 9:case 11:

Numdays = 30;

Break

Case 2:

if (((year% 4 = = 0) &&! ( Year% 100 = = 0)) | | (Year% 400 = = 0))

numdays = 29;

Else

Numdays = 28;

Break

Default

SYSTEM.OUT.PRINTLN ("Invalid Month");

Break

}

System.out.println ("Number of days =" + numdays);

}

}

Output: Number of days = 29

Use a string in a switch statement

Java7 and later, you can use a string object in a switch statement expression. The following example shows the number of months through a string.

public class stringswitchdemo{

public static int Getmonthnumber (String month) {

int num = 0;

if (month = = null)

return num;

Switch (Month.tolowcase ()) {

Case "January":

num = 1;

Break

Case "February":

num = 2;

Break

Case "March":

num = 3;

Break

Case "April":

num = 4;

Break

Case ' may ':

num = 5;

Break

Case "June":

num = 6;

Break

Case "July":

num = 7;

Break

Case "August":

num = 8;

Break

Case "September":

num = 9;

Break

Case "October":

num = 10;

Break

Case "November":

num = 11;

Break

Case "December":

num = 12;

Break

Default

num = 0;

Break

}

return num;

}

public static void Main (string[] args) {

String month = "August";

int num = stringswitchdemo.getmonthnumber (month);

if (num = = 0) {

SYSEM.OUT.PRINTLN ("Invalid Month");

}else{

SYSTEM.OUT.PRINTLN (num);

}

}

}

Output: 8

The string in the switch expression is compared to each case label expression as if it were using the String.Equals method. In order to ignore the case, the month parameter is converted to lowercase (using the Tolowcase method), and the strings are all lowercase.

Note that the switch expression is checked for NULL in this example. Ensure that the switch expression is not NULL to prevent NULL pointer exceptions.

While and Do-while statements

The While statement executes the statement in the block all the time when the condition is true. As follows:

while (expression) {

Statement (s)

}

While statements evaluate the value of an expression, the expression must return a Boolean value. If the expression value is true, the statement in the while block is executed. The while statement always tests the expression and executes the statement in the while block until the value of the expression is false. The following code prints 1 through 10 using the while statement.

Class whiledemo{

public static void Main (sring[] args) {

int count = 1;

while (Count < 11) {

System.out.println (count);

count++;

}

}

}

You can use the while statement to implement an infinite loop:

while (true) {

}

Java also provides a do-while statement, as follows:

do{

statement (s);

}while (expression);

The difference between a while statement and a do-while statement is that the do-while evaluates its expression at the bottom of the loop, while the while evaluates the expression at the top. Therefore, the Do-while statement executes at least one of its blocks at a time. The following code:

Class dowhiledemo{

public static void Main (string[] args) {

int count = 1;

do{

System.out.println (count);

count++;

}while (COUNT<11);

}

}

For statement

The For statement provides a concise way to traverse a range of values. It is typically used in a program to loop, because in a for statement, it repeats until a certain condition is met. The usual for statement is as follows:

for (initialization;termination;increment) {

statement (s);

}

Note When using this version of the FOR statement:

The initialization expression initializes the loop, which executes once at the beginning of the loop;

When the terminating expression evaluates to False, the loop terminates;

After each iteration of the loop, the increment expression is executed, which is especially useful for increasing or decreasing a value;

The following program uses a generic for statement to print 1 to 10:

Class fordemo{

public static void Main (string[] args) {

for (int i = 0; i < i++) {

System.out.print (i+ "");

}

}

}

Output: 1 2 3 4 5 6 7 8 9 10

Notice how a variable is declared in the initialization expression. The scope of this variable is extended from its declaration to the end of the block, managed by the for statement, so the variable can be used by terminating the expression and increasing the expression. If the variable that controls the For statement does not need to be used outside the loop, then this variable is best declared in an initialization expression. Variable names I, J, K are typically used for loops, and they are declared in an initialization expression to limit their life cycle and reduce errors.

The three expressions in the For statement are optional, and an infinite loop statement is defined as follows:

for (;;;) {

}

The For statement also has other forms, for collection and array traversal. These forms are used as an enhanced version of the For statement to make your loops more compact and readable. As below, consider the following array, which has numbers 1 through 10:

int[] numbers = {1,2,3,4,5,6,7,8,9,10};

The following code uses the enhanced for statement to traverse the array:

Class enhancedfordemo{

public static void Main (string[] args) {

int[] numbers = {1,2,3,4,5,6,7,8,9,10};

for (int item:numbers) {

System.out.print (item+ "");

}

}

}

Output: 1 2 3 4 5 6 7 8 9 10

We recommend using the enhanced for statement as much as possible.

Branch statements

The break statement has two forms: marked and unmarked. You have seen unmarked in the switch statement. You can also use an unmarked break to terminate a for, while, Do-while loop with the following code:

Class breakdemo{

public static void Main (string[] args) {

Int[] arrayofints = {32,87,3,589,

12,1076,2000,

8,622,127};

int searchfor = 12;

int i;

Boolean foundit = false;

for (i = 0; i < arrayofints.length; i++) {

if (arrayofints[i] = = searchfor) {

Foundit = true;

Break

}

}

if (Foundid) {

System.out.println ("Found" + searchfor + "at index" + i);

}else{

System.out.println (Searchfor + "not in the array");

}

}

}

Output: Found at index 4

The program looks for the number 12 in the array. Break statement, which terminates the for loop when the number is found, and the control flow jumps to the statement following the for loop.

An unmarked break statement terminates the inner switch, for, and while, do-while statements, while a marked break statement terminates the outer loop statement. The following program is similar to the above, but uses a nested for loop to find a value in a two-dimensional array. After the value is found, a marked break terminates the outer loop (labeled "Search").

Class breakwithlabeldemo{

public static void Main (string[] args) {

Int[][] Arrayofints = {{32,87,3,589},{12,1076,2000,8},{622,127,77,955}};

int searchfor = 12;

int i;

int j = 0;

Boolean foundit = false;

Search

for (i = 0; i < arrayofints.length; i++) {

for (j = 0; J < Arrayofints[i].length; J + +) {

if (arrayofints[i][j] = = searchfor) {

Foundit = true;

Break search;

}

}

}

if (Fountid) {

System.out.println ("Found" + searchfor + "at index" + i + "," + j);

}else{

System.out.println (Searchfor + "not in the array");

}

}

}

Output: Found at index 1, 0

The break statement terminates the token statement, which does not return the control flow to the tag statement. The control flow jumps to a later statement in the markup statement.

Use the continue statement in a for, while, Do-while Loop to skip the current traversal. The untagged form jumps to the end of the inner Loop and calculates the Boolean expression that controls the loop. The following program evaluates to a string that appears with the letter p. When the current letter is not the P,continue statement skips the remainder of the loop and processes the next letter. If it is P, count plus 1.

Class continuedemo{

public static void Main (string[] args) {

String searchMe = "Peter Piper picked a" + "Peck of pickled Peppers";

int max = Searchme.length ();

int numps = 0;

for (int i = 0; i < max; i++) {

if (Searchme.charat (i)! = ' P ')

Continue

numps++;

}

System.out.println ("found" + Numps + "p in the string");

}

}

Output: Found 9 p in the string

To make the effect clearer, try removing the continue and re-executing. The result becomes 35 p.

A tagged continue statement skips the current traversal from the outer loop of the tag. The following example uses nested loops to look up substrings in a string. Two nested loops are required: one loops through the searched string, and one iterates through the substring. The following code skips the traversal of the outer loop with a tagged continue.

Class continuewithlabeldemo{

public static void Main (string[] args) {

String searchMe = "Look for a substring in me";

String substring = "Sub";

Boolean foundit = false;

int max = Searchme.length ()-substring.length ();

Test

for (int i = 0; i < max; i++) {

int n = substring.length ();

int j = 0;

int k = i;

while (n--! = 0) {

if (Searcchme.charat (k++)! = Substring.charat (j + +)) {

Continue test;

}

}

Foundit = true;

Break test;

}

System.out.println (Foundit? "Found it": "Not found it");

}

}

Output: Found it

The last branch statement is the return statement. The return statement exits from the current method, and the control flow returns to the location of the method call. The return statement has two forms: one that returns a value, and one that does not return a value. The return value (or an expression that evaluates to a value) only needs to be followed by the return value.

return ++count;

The data type of the returned value must match the type of the return value of the method declaration. When the method declares void, returns that do not return a value are used.

Return

We'll talk about the method later.

Summary of Control flow statements

The If-then statement is the most commonly used in all control flow statements. It tells your program to execute a piece of code when your condition evaluates to True. The If-then-else statement provides a second execution path when the IF clause evaluates to FALSE. Unlike the If-then and If-then-else,switch statements, any number of execution paths are allowed. When a condition is true, the while and Do-while statements execute a block of statements. The difference between while and Do-while is that the do-while evaluates its expression at the bottom of the loop, not the top. Therefore, the block statements in the Do-while are executed at least once. The For statement provides a concise way to traverse a range of values. It has two forms, one for the collection and the other for the array.

(translation) Second Language Foundation (4)--Control flow statement

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.