Switch and loop statements for Java Process Control statements

Source: Internet
Author: User
Tags goto

1.switch

switch (expression) {case value 1: statement body 1;     Break          Case Value 2: statement body 2;     Break          ... default: statement body N; break;}

Format Explanation:

Switch indicates that this is a switch statement

A) The value of the expression: Byte,short,int,char

b) JDK5 can be enumerated after

c) After JDK7 can be a string

The case is followed by the value to be compared with the expression

Statement body part can be one or more days statement

Break indicates the meaning of the interrupt or end, and can end the switch statement

The default statement means that when all cases do not match, the content is executed, similar to the else of the IF statement


Execution process

First, the value of the expression is calculated

Second, and the case in turn, once there is a corresponding value, will execute the corresponding statement, in the course of execution, encountered a break will end.

Finally, if all the case does not match the value of the expression, the body part of the default statement is executed and the program ends.


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/87/51/wKioL1fdNHvQOnLEAABy8-AsMK4879.png "title=" Qq20160917201751.png "alt=" Wkiol1fdnhvqonleaaby8-asmk4879.png "/>


Precautions:

A case can be followed only by a constant, not a variable, and a value that follows multiple occurrences cannot appear the same.

Default can be omitted, generally not recommended.

Break can be omitted, generally not recommended.

Default can appear anywhere in the switch statement.

The end condition of the switch statement: 1. Encountered a break, 2. Executes to the end of the program.

import java.util.scanner;/** *  keyboard input A data, according to this data, we output the corresponding day of the week  *        Keyboard input 1, corresponding output Monday  *       keyboard input 2, corresponding output Tuesday  *       ... *       keyboard input 7, corresponding output Sunday  */public class  Switchdemo {    public static void main (String[] args) {         scanner input  = new scanner (System.in);         system.out.print ("Please enter Number:");         int day = input.nextint ();         string str =  "";         switch (day) {             case 1:                 str =  "Monday";                 break;            case  2:                str  =  "Tuesday";                 break;            case 3:                 str =  "Wednesday";                 break;             case 4:                 str =  "Thursday";                 break;             case 5:                 str =  "Friday";                 break;            case  6:                str  =  "Saturday";                 break;            case 7:                 str =  "Sunday";                 break;             default:                 str =  "Invalid input data";                 break ;        }         system.out.println (str);     }}


When making a judgment, we have two options, the IF statement and the switch statement, so how do we choose which statement to use?

The IF statement uses the scenario:

For the result is a Boolean type of judgment

For a range of judgments

Judging for several constant values

Switch statement usage scenario:

Judging for several constant values


2. Cyclic 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 repeatedly executed, it is necessary to change the loop 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 before the next loop determines whether the condition executes before the loop body is completed in turn. By controlling the variables in the loop condition, the loop ends at the appropriate time.


3. Loop structure (for Loop statement)

For Loop statement format:

for (initialize statement; Judge conditional statement; Control condition statement) {loop body statement;}

Execution process:

1. Execute initialization statements

2. Execute the JUDGMENT condition statement to see if the result is true or false, if it is false, the loop ends, or if true, the loop executes.

3. Executing the Loop body statement

4. Execute the CONTROL condition statement

5. Return to 2 to continue


650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/87/52/wKioL1fdRAGAi7r1AABijocM4pU137.png "title=" Qq20160917212403.png "alt=" Wkiol1fdragai7r1aabijocm4pu137.png "/>


/** * For loop */public class Fordemo {public static void main (string[] args) {for (int i = 0;i<4;i++) {        System.out.println ("Hello World"); }    }}

Precautions:

1. The result of judging a conditional statement is a Boolean type.

2. Loop body Statement If it is a statement, the curly braces can be omitted, and in the case of multiple statements, the curly braces cannot be omitted. Never omit the suggestion.

/** *  in console input 1-10 */public class fordemo {     public static void main (String[] args) {         for (int i = 1;i<=10;i++) {             system.out.println (i);        }     }} 
/** *  for 1-10 and  */public class fordemo {     public static void main (String[] args) {         int sum = 0;        for (int  i = 1;i<=10;i++) {             sum += i;        }        &NBSP;SYSTEM.OUT.PRINTLN (sum);     }} 
/** *  the sum of odd and even numbers of 1-100 and  */public class fordemo {    public  static void main (String[] args) {        int  odd = 0;        int even = 0;         for (int i =0;i<=100;i++) {             if (i %2 == 0) {                 even += i;             }else {                 odd += i;             }        }         system.out.println ("Odd and is" +odd+ ", Even and" +even ";     }} 
/** *  asks 5 factorial  *   what is factorial?  *      n! = n* (n-1)! *      n ! = n * (n-1) * (n-2) *...*3*2*1 */public class fordemo {     public static void main (String[] args) {         int num = 1;        for  (int i =1; i<=5;i++) {            num *= i;         }        system.out.println ( num);     }} 
/** *  Daffodil number  *       the so-called Narcissus number is a three-digit number, the cubic of its numbers and equal to the number itself.  *       Example: 153 is a narcissus number  *      153 =  1*1*1 + 5*5*5 +3*3*3 */public class ForDemo {     Public static void main (String[] args) {        for (int i = 100;i<=999;i++) {            int baiwei = i /  100;            int shiwei =  I / 10 % 10;            int  gewei = i % 10;             int result = baiwei * baiwei * baiwei + shiwei * shiwei * shiwei + gewei * gewei * gewei;             if (I == result) {                 system.out.println (i+ "is the number of daffodils");             }        }     }}


4. Loop structure (while loop statement)

While loop statement format:

initialization statement; while (judging conditional statement) {loop body statement; Control condition statement;}

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/87/52/wKioL1fdVaHjxabBAABNqQmHZPQ689.png "title=" Qq20160917223919.png "alt=" Wkiol1fdvahjxabbaabnqqmhzpq689.png "/>



What is the difference between a for loop and a while loop?

Use difference: Control the variable that the condition statement controls, after the For loop end, then can not be accessed again, and while the end of the loop, but also continue to use, if you want to continue to use, use while, otherwise it is recommended to use the For loop, because the For loop ends, the variable disappears from memory , it can improve the efficiency of memory usage.

Scene difference: The For loop is suitable for a range of judgments, of course, the range is a number, while the while loop is suitable for judging ambiguous operations. For example: You go for ten laps, you use a For loop, you run until you die, you use the while loop.

/** *   the highest mountain in China is Mt. Everest: 8848 m, now I have a paper large enough to be 0.01 meters thick.  *   Excuse me: how many times can I fold it to ensure that the thickness is not lower than the height of Mount Everest?  *   Analysis:  *      1. Define a statistic variable, the default value bit 0 *       2. The highest mountain is Mt. Everest: 8848 m, which is the final thickness  *         I now have a large enough paper, thickness: 0.01 meters, which is the initial thickness.  *      3. How many times can I fold it to cover a height of not less than Everest  *      What is the change in the     folding sequence? is twice times the thickness of the previous one.  *      4. As long as the thickness of each change does not check the height of Mount Everest, it folds  *       5. Output statistic Variables  */public class WhileDemo {    public static  Void main (String[] args) {        int count =  0;        double end = 8848;         double start = 0.01;  &nbSp;     while (start < end) {             count ++;             start *= 2;        }         system.out.println (count);     }}


5. Cyclic structure (do...while structure)

DO...WHILE Loop structure Format:

initialization condition; do{loop body statement; Control condition statement;} while (judging conditional statements);

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/87/56/wKiom1fdX2OhBb8EAABW2Z0D8pc903.png "title=" Qq20160917232058.png "alt=" Wkiom1fdx2ohbb8eaabw2z0d8pc903.png "/>

The difference of circular structure and the matters needing attention

Three kinds of circular statements can actually complete a line of functions, that is, 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.

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

/** * Output 4 rows 5 columns of Stars */public class Forfordemo {public static void main (string[] args) {for (int i = 0;i<4;i++) {            for (int y = 0;y<5;y++) {System.out.print ("*");        } System.out.println (); }    }}


6. Jump Control Statements

Goto in Java is a reserved word and cannot be used at this time. Although there is no goto to enhance the security of the program, but also brings a lot of inconvenience, for example, I want to a loop at a certain point in time to end, and now do not do this thing. To compensate for this flaw, Java provides break,continue and return to implement the jump and terminal of the control statement.




This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1853470

Switch and loop statements for Java Process Control statements

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.