The circular structure Statement of Java Syntax Foundation _java

Source: Internet
Author: User
Tags goto memory usage tag name

First, the circulation structure

A circular statement can be used to satisfy a cyclic condition repeated execution of a piece of code, the repeated execution of the code is called the Loop body statement, when the recurrence of the loop body, the need to be in the appropriate time to change the cyclic judgment condition to false, 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.

To judge a conditional 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 section is executed before the next cyclic judgment condition is executed after the end of the loop body. By controlling the variables in the loop condition, the loop ends at the right time.

Eg: in the console output 10 times "HelloWorld",

Initialization statement: The definition is initialized to the first time.

To judge a conditional statement: The number of times cannot exceed 10 times.

Loop Body statement: Output "HelloWorld" statement.

Control Conditional statement: The number of times changes to the next time.

Second, loop structure (for Loop statement)

For Loop statement format:

for (initialization statement; Judgment condition statement; Control condition statement) {
Circular body statement;
}

Execution process:

A: Execute the initialization statement

B: Execute the JUDGMENT condition statement to see if the result is true or false: if False, the loop ends, and if true, continue execution.

C: Execute the Loop body statement

D: Execute control condition statement

E: Go back to B continue

Flow chart:

Precautions:

(1) To determine the result of a conditional statement is a Boolean type

(2) If the circular body statement is a statement, the braces can be omitted; if it is more than one statement, the curly braces cannot be omitted. It is recommended that you never omit.

(3) Generally speaking: there is no semicolon with left curly braces, there is no left curly brace with semicolon

code example:

1. Find the even number between 1-100 and:


  /* Requirements:
    A: 1-100 of the sum.
    B: Find the sum of even and/or
class ForTest1 {public
  static void Main (string[] args) {
    //1-100 for 1-100.
    int sum1 = 0;
    
    for (int x=1; x<=100; x + +) {
      sum1 +=x;
    }
    
    System.out.println ("1-100 of the sum is:" +SUM1);
    System.out.println ("------------------");
    
    Find out 1-100 even and
    /or 1
    int sum2 = 0;
    
    for (int x=1; x<=100; x + +) {
      if (x%2 = 0) {
        sum2 = = x;
      }
    }
    
    System.out.println ("The sum of the 1-100 even numbers is:" +sum2);
    System.out.println ("------------------");
    
    Mode 2
    int sum3 = 0;
    
    for (int x=0; x<=100; x+=2) {
        sum3 = = x;
    }
    
    System.out.println ("The sum of the 1-100 even numbers is:" +sum3);
    System.out.println ("------------------");
  }

2, to find the factorial of 5:


  /* Requirements: the factorial of 5.
  
  What is factorial
    ? N! = N (n-1)! Rule
    n! = n (n-1) * (n-2) *...*3*2*1
    
  summation thought. To
  seek factorial thought.
* *
class ForTest2 {public
  static void Main (string[] args) {
    //define final result variable
    int jc = 1;
    
    Here the X can actually start at 2
    //for (int x=1; x<=5; x + +) for 
    
    (int x=2; x<=5; x + +) {
      JC *=x;
    }
    
    System.out.println ("1-5 factorial is:" +JC);
  }


3, in the console output all the "Narcissus number":



  /* Requirements: In the console output all the "Narcissus number"
  
  Analysis:
    We do not know what is called "Narcissus number", what do you want me to do?
    
    The so-called Narcissus number refers to a three-digit number, its numbers of cubic and equal to the number itself.
    Example: 153 is a narcissus number.
    153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + + MB = 153

    A: The three digits actually tell us the scope.
    B: In the For loop we can get every three digits
     but the trouble is how to get this three-digit, 10, hundreds of data
     
     How do we get a data of one, 10, hundred
      ? Suppose there is one data: 153
      ge:  153%10 = 3
      shi:153/10%10 = 5
      bai:153/10/10%10 = 1
      qian:x/10/10/10%10
      Wan:x/10/10/10/10%10 ...

    C: Let Ge*ge*ge+shi*shi*shi+bai*bai*bai and the data compare
     if the same, the data in the console output.
*
/class ForTest3 {public
  static void Main (string[] args) {
    //three digits actually tells us the scope. for
    (int x=100; x<1000; x + +) {
      int ge = x%10;
      int shi = x/10%10;
      int bai = x/10/10%10;
      
      Let Ge*ge*ge+shi*shi*shi+bai*bai*bai and the data compare if
      (x = = (Ge*ge*ge+shi*shi*shi+bai*bai*bai)) {
        //if the same, The data is output in the console.
        System.out.println (x);
      }
    }
  }

Third, loop structure (while loop statement)

While loop statement format:

while (judgment condition statement) {
Circular body statement;
}

Extended format
Initialization statement;
while (judgment condition statement) {
Circular body statement;
Control conditional statement;
}

Flow chart:

The difference between a for loop and a while loop:

The FOR Loop statement and the while Loop statement can be converted equivalently, but some are still in the community.

(1) Use the difference:

The variable controlled by the control condition statement can no longer be accessed after the For loop ends, while the while loop ends and continues to be used, if you want to continue using it, use a while, otherwise it is recommended for. The reason for this is the end of the for loop, which disappears from memory and can improve the efficiency of memory usage.

(2) Scene difference:

The For loop is suitable for a range judgment operation while loop is suitable for judging times ambiguous operation

code example:

China's highest peak is Mount Everest: 8848m, I now have a large enough paper, thickness: 0.01m. Excuse me, how many times can I fold to ensure that the thickness is not less than the height of Mt. Everest?

* The
  highest peak in China is Mount Everest: 8848m, I now have a large enough paper, thickness: 0.01m.
  excuse me, how many times can I fold to ensure that the thickness is not less than the height of Mt. Everest?

  Analysis:
    A: Define a statistical variable, the default value is 0
    B: The highest peak is Mount Everest: 8848m This is the final thickness
     I now have a large enough paper, thickness: 0.01m This is the initial thickness of
    C: How many times I fold, To ensure that the thickness is not less than the height of Mount Everest?
     Folding one at a time what's the difference? It's twice times thicker than before.
    D: As long as the thickness of each change does not exceed the height of Everest, the folding, statistical variables + +
    E: Output statistic variables.
*

/class WhileTest01 {public
  static void Main (string[] args) {
    //define a statistic variable, the default value is 0
    int count = 0 ;
    
    The highest peak is Mount Everest: 8848m This is the final thickness
    //I now have a large enough paper, thickness: 0.01m This is the initial thickness
    //For simplicity, I turned 0.01 to 1, and the same 8848 became 884800
    int end = 884800;
    int start = 1;
    
    while (start<end) {
      //As long as the thickness of each change does not exceed the height of Mount Everest, fold, statistical variable + +
      count++;
      
      Folding one at a time what's the difference? It's twice times thicker than before.
      start *= 2;
      
      System.out.println ("First" +count+ "secondary thickness is" +start);
    }
    
    The output statistic variable.
    System.out.println ("to Stack" +count+);
  }


IV. Circular Structure (Do...while Loop statement)

Basic format:

do {

Circular body statement;

}while ((judging conditional statement); /code]

Extended format:

Initialization statement;

do {

Circular body statement;

Control conditional statement;

while ((judging a conditional statement); /code]

Flow chart:

The difference of circulation structure and matters needing attention:

Three kinds of circular statements can actually accomplish the same function, that is to say, equivalent conversion, but there are small differences:

The Do...while loop will perform at least one loop body at a time. The For loop and the while loop execute the loop body only when the condition is set

1, Attention matters:

Write programs give priority to the for loop, then consider the while loop, and finally consider the Do...while loop.

The following code is a dead loop:

while (true) {}

for (;;) {}

2, the loop of nested use: is the circular statement of the loop itself is a circular statement

(1) Topic One: Please output a 4 line 5 star (*) Pattern:

Tip: Outer loop control row number, Inner loop control column number


  /* Requirements: Please output the following shape * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
ForForTest01 {public
  static void Main (string[] args) {//
    by simple observation, we see that this is a row is 5, the number of columns is the shape of the change
    //We first print out a 5 row 5 column shape for
    (int x=0; x<5; x + +) {for
      (int y=0; y<5; y++) {
        System.out.print ("*");
      }
      System.out.println ();
    }
    
    System.out.println ("--------------");
    
    We implemented a 5-row 5-Column shape
    //But that's not
    what
    we want//we want to change the number of columns//columns. First line: 1 column  y=0,y<=0,y++
    //second line: 2 column  y=0,y<=1,y++
    //Third row: 3 column  y=0,y<=2,y++
    // Line four: 4  y=0,y<=3,y++
    //Line Fifth: 5 columns  y=0,y<=4,y++//
    in view of the change in the outer circulation x happens to be x=0,1,2,3,4
    // So this final version of the program is as follows for
    (int x=0; x<5; x + +) {for
      (int y=0; y<=x; y++) {
        System.out.print ("*");
      }
      System.out.println ();}}

(2) Topic Two: Output 99 multiplication table in the console:


  /* Requirements: Output 99 multiplication tables in the console.
  
  First we write the 99 multiplication table:
    1*1=1
    1*2=2  2*2=4
    1*3=3  2*3=6  3*3=9 1*4=4 2*4=8  4*4=16 ...
    1*9=9  2*9=18  3*9=27 ...
    
  We first see this 99 multiplication table is such a shape: * * * * * * * * * * * * * * * * * * * * *
    *******
    ********
    
  Note:
    ' \x ' x indicates arbitrary, this practice is called the transfer character.
    
    ' \ t '  a tab position (Tabtab key)
    ' \ R '  enter
    ' \ n ' linefeed/
class ForForTest02 {
  public static void Main (string[] args) {for
    (int x=0; x<9; x + +) {for
      (int y=0; y<=x; y++) {
        System.ou T.print ("*");
      }
      System.out.println ();
    }
    System.out.println ("--------------");
    In order to use the data, we start with 1 for
    (int x=1; x<=9; x + +) {for
      (int y=1; y<=x; y++) {
        System.out.print (y+ "*" +x+ "=" + y*x+ "\ t");
      }
      System.out.println ();}}

Operation Effect:

Six, jump control statements:

As we have already mentioned, Goto in Java is reserved and cannot be used at this time. Although there is no goto statement to enhance the security of the program, but also bring a lot of inconvenience, for example, I want to be in a certain cycle when the end of a certain step, now can not do this thing. To make up for this flaw, Java provides break,continue and return to implement the jump and interrupt of the control statement.

Break Interrupt
Continue continue
return returns

1, Jump control statement (break):

Use scene for break:

~ In the SELECT structure switch statement

~ in a circular statement (the case where the if judgment is added to the circular statement)

Note: There is no point in leaving the use scene

The function of the break:

A: Jump out of A single layer cycle

B: Jump out of multiple loops

In order to achieve this effect, you must know one thing. The statement with the label. Label name to conform to Java naming rules

Format:

Label Name: statement

code example:

/*
  control Jump statement:
    break: Interrupt
    continue: Continue
    return: Back
  
  break: Meaning of interrupt
  use scene:
    a:switch statement
    B: Loop statement.
      (If the case is added to the loop statement)
    Note: Leave the above two scenes meaningless.
    
  How to use it?
    A: Jump out
    of a single layer of cycle B: jump out of multi-layer loops
      to achieve this effect, you must know something. The statement with the label.
      format:
        tag name: statement
*/
class Breakdemo {public
  static void Main (string[] args) {
    //in switch or loo P external interrupt
    //break;
    
    Jump out of one-layer loop for
    (int x=0; x<10; x + +) {
      if (x = = 3) {break
        ;
      }
      System.out.println ("HelloWorld");
    }
    
    System.out.println ("over");
    System.out.println ("-------------");
    
    Jump out of Multilayer loops
    wc:for (int x=0; x<3; x + +) {
      nc:for (int y=0; y<4; y++) {
        if (y = = 2) {
          //break NC;
          Break WC;
        }
        System.out.print ("*");
      }
      System.out.println ();}}

Line 38th, we add a label to the outer loop called WC, and then jump out of the label on Line 42nd.

Operation Effect:

Note: In actual development, the function of jumping multi-layer loop is hardly used.

2, Jump control statement (continue):

Continue usage Scenarios:

It doesn't make sense to leave the existence of a usage scene in a loop statement.

The difference between continue and break:

Break out of a single cycle continue jump out of a cycle, into the next execution.

The effect is as follows:

Interview questions:

for (int x=1; x<=10; x + +) {
    if (x%3==0) {
      //write code here

    }
    System.out.println ("Java Learning");
  }

At line 4th of the above code, fill in one line of code to satisfy the condition:

I want to output 2 times in the console: "Java learning" break;

I want to output 7 times in the console: "Java learning" continue;

I want to output 13 times in the console: "Java Learning" System.out.println ("Java Learning");

3, Jump control statement (return)

Return keyword is not to jump out of the loop body, the more commonly used function is to end a method, that is, exit a method, jump to the top of the call method.

Plainly: The return function is not to end the loop, but to end the method.

The effect is as follows:

Looping statements combine the practice of break:

Interview questions: Xiao Fang's mother gave her 2.5 yuan every day, she will save, but, whenever this day is the 5th day of saving or a multiple of 5, she will spend 6 yuan, excuse me, after how many days, Xiao Fang can save to 100 yuan.

Code implementation:

/* Requirements: Xiao Fang's mother gave her 2.5 yuan a day, she will save, but, whenever this day is the 5th day of savings or a multiple of 5, she will spend 6 yuan, please, after how many days, Xiao Fang can save to 100 yuan.
    Analysis: A: Xiao Fang's mother gave her 2.5 yuan a day double Daymoney = 2.5;
    B: She'll save it. Double daysum = 0;
    C: storage of int daycount = 1 from First day;
      D: After how many days, Xiao Fang can save to 100 yuan of money.
    Double result = 100;
        E: This day is the 5th day of saving or a multiple of 5, she will spend 6 yuan, indicating to judge the value of Daycount, if the 5 division is divided by 6 yuan.
     Daysum-= 6;
    This also implies a problem, that is, if not 5 multiples of the day, the money to add daysum + = Daymoney;
F: Because I do not know how many days, so I use the dead loop, once more than 100 yuan I will exit the cycle.
    
    */class Whiledemo {public static void main (string[] args) {//Every day the money to be stored is 2.5 yuan double Daymoney = 2.5;
    
    The initial value for saving is 0 double daysum = 0;
    
    Store int daycount = 1 from First day;
    
    The final store is no less than 100 and does not store int result = 100;
      
      Because I do not know how many days, so I use the Dead loop, while (true) {//sum money daysum + = Daymoney;
      Once I'm over 100 yuan, I'm out of the loop.
        if (daysum >= result) {System.out.println ("spent a total of" +daycount+ "Days stored 100 Yuan");
      Break } if (daycount%5 = 0) {//Flowers to6 Yuan Daysum = 6;
      System.out.println ("The first" +daycount+ "smallpox 6 yuan money");
    }//days change daycount++;
 }
  }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.