3. Java cyclic notes

Source: Internet
Author: User
Tags array definition

3. Java cyclic notes

1. Loop type:

1. for Loop

1 class For {2 public static void main (String [] args) {3 System. out. println ("Hello World! "); 4 System. out. println (" Hello World! "); 5 System. out. println (" Hello World! "); 6 System. out. println (" Hello World! "); 7 System. out. println (" I Am a separator ~~~~~~~~~~~~~~~~~~~~~~~~ "); 8 for (int I = 0; I <4; I ++) {9 System. out. println (" Hello World! "); 10} 11} 12}

Running result:

2. while (){}

1 class TestWhile {2 public static void main (String [] args) {3 // output of an even number within 100 4 int I = 1; 5 int sum = 0; 6 while (I <= 100) {7 if (I % 2 = 0) {8 System. out. println (I); 9 sum + = I; 10} 11 I ++; 12} 13 System. out. println (sum); 14 // System. out. println (I); 15} 16}

Running result:

3. do {} while ()

 1 class DoWhile{ 2     public static void main(String[] args) { 3         int i = 1; 4         do{ 5             if(i % 2 == 0){ 6                 System.out.print(i + "\t"); 7             } 8             i++; 9         }while(i <= 100);10     }11 }

Running result:

Ii. format:

All loop structures must contain the following four parts:

1. initialization conditions;

2. cyclic conditions;

3. iteration conditions;

4. Loop body;

1. for Loop format:

1/* 2 all cycle structures must contain the following four parts: 3 1. Initialization Conditions; 4 2. cycle conditions; 5. iteration conditions; 6 4. cycle body; 7. the correspondence between the Code and the format is as follows: 8 1. initialization condition = int I = 0; 9 2. Loop condition = I <4; 10 3. Iteration condition = I ++; 11 4. Loop body = System. out. println ("Hello World! "); 12 */13 class For {14 public static void main (String [] args) {15 for (int I = 0; I <4; I ++) {16 System. out. println ("Hello World! "); 17} 18} 19}

2. while loop format:

1/* 2 all cycle structures must contain the following four parts: 3 1. Initialization Conditions; 4 2. cycle conditions; 5. iteration conditions; 6 4. cycle body; 7. the correspondence between the Code and the format is: 8 1. initialization condition = int I = 1; int sum = 0; 9 2. Loop condition = I <= 100; 10 3. Iteration condition = I ++; 11 4. Loop body = if statement; 12 */13 class TestWhile {14 public static void main (String [] args) {15 // output 16 int I = 1 for an even number less than 100; 17 int sum = 0; 18 while (I <= 100) {19 if (I % 2 = 0) {20 System. out. print (I + "\ t"); 21 sum + = I; 22} 23 I ++; 24} 25 System. out. print (sum); 27} 28}

3. do {4 3} while (2 );

/* All cycle structures must contain the following four parts: 1. Initialization Conditions; 2. Loop conditions; 3. iteration conditions; 4. Loop body; in this Code, the correspondence with the format is: 1. initialization condition = int I = 1; 2. Loop condition = I <= 100; 3. Iteration condition = I ++; 4. Loop body = if statement; */class TestDoWhile {public static void main (String [] args) {int I = 1; do {if (I % 2 = 0) {System. out. println (I) ;} I ++ ;}while (I <= 100); int j = 10; do {System. out. println (j); j ++;} while (j <10); while (j <10) {System. out. println (j); j ++ ;}}}

  Note:

1. Different cyclic structures can be converted to each other;

2. Difference Between while and do-while: the do-while program will be executed at least once;

3. nested loop:

Note: You can declare a loop in the loop structure, so that the inner loop structure acts as the loop body of the outer loop as a whole. If the outer loop executes m times, the inner loop executes N times, the entire program executes m * n times.

It can be understood as the number of rows in the outer loop and the number of columns in the inner loop;

Example:

1 class TestFor2 {2 public static void main (String [] args) {3 for (int j = 0; j <4; j ++) {// number of rows in the outer loop control 4 for (int I = 0; I <5; I ++) {// number of rows in the inner loop control 5 System. out. print ("*"); 6} 7 System. out. println (); 8} 9} 10}

Running result:

Exercise questions

1. Multiplication table

 1 class TestJiuJiu { 2     public static void main(String[] args) { 3         for(int i = 1;i <= 9;i++){ 4             for(int j = 1;j <= i;j++){ 5                 System.out.print(i + "*" + j + "=" + i*j + "\t"); 6             } 7         System.out.println(); 8         } 9     }10 }

Running result:

2. output the prime number within 100 (implemented in two methods)

First:

1 class TestPrimeNumber {2 public static void main (String [] args) {3 boolean flag = false; 4 long start = System. currentTimeMillis (); 5 for (int I = 2; I <= 100000; I ++) {// implement traversal of natural numbers within 100. 6 // determine whether I is a prime number 7 for (int j = 2; j <= Math. sqrt (I); j ++) {8 if (I % j = 0) {9 flag = true; 10 break; 11} 12} 13 if (! Flag) {14 System. out. println (I); 15} 16 flag = false; 17} 18 long end = System. currentTimeMillis (); 19 System. out. println ("the time spent is:" + (end-start); 20} 21}

Running result: because there is too much data, the operation time is used to represent

Second: This method is mainly used to display the running efficiency, which is also expressed by running time.

 

Class TestPrimeNumber1 {public static void main (String [] args) {// boolean flag = false; long start = System. currentTimeMillis (); l: for (int I = 2; I <= 100000; I ++) {// implement the traversal of a natural number less than 100 // determine whether I is a prime number for (int j = 2; j <= Math. sqrt (I); j ++) {if (I % j = 0) {// flag = true; // break; continue l ;}// if (! Flag) {// System. out. println (I); // flag = false;} long end = System. currentTimeMillis (); System. out. println ("the time spent is:" + (end-start ));}}

Running result:

Iv. Infinite Loops

To use an infinite loop, change the cycle condition of the loop to true (For more information about the code format, see section 2.), But it should be noted that the cycle termination conditions (using the break keyword) must be provided within the infinite loop results; otherwise, the program will be executed without limit to form an endless loop;

V. break and continue:

1. break:

1. It is used in the swich-case structure or cyclic structure;

2. In the loop structure, once the break is executed, the current loop jumps out.

2. continue:

1. Use in the loop structure;

2. In the loop structure, once the execution reaches the continue, the current loop exists;

3. In a nested loop, use the break and continue with tags.

  Example:

1 class TestPrimeNumber1 {2 public static void main (String [] args) {3 // boolean flag = false; 4 long start = System. currentTimeMillis (); 5 l: for (int I = 2; I <= 100000; I ++) {// implement traversal of natural numbers within 100. 6 // determine whether I is a prime number 7 for (int j = 2; j <= Math. sqrt (I); j ++) {8 if (I % j = 0) {9 // flag = true; 10 // break; 11 continue l; 12} 13} 14 // if (! Flag) {15 // System. out. println (I); 16 //} 17 // flag = false; 18} 19 long end = System. currentTimeMillis (); 20 System. out. println ("the time spent is:" + (end-start); 21} 22}

Note: Pay attention to the 5th lines of code (L: for (int I = 2; I <= 100000; I ++)) And 11th lines of code (Continue l;),Write an l: Label in front of the fifth line of code, and then call it at line 1. If the program is executed here, the loop is automatically exceeded and then executed from the fifth line;

Vi. array:

  1. Definition: A combination of data of the same data type.

Do not use the array definition method:

int i1 = 1;int i2 = 2;int i3 = 3;

Array definition:

      1. Static initialization: declare and initialize an array and assign values to the corresponding elements of the array;

Int [] scores = new int [] {72,90, 59 };

      2. Dynamic initialization: Separate declaring and initializing arrays from assigning values to corresponding elements of arrays;

Int [] scores1 = new int [3];

Socres1 [0] = 72;

Socres1 [1] = 90;

Socres1 [2] = 59;

 

  2. array initialization problems (the following initialization methods are incorrect ):

String [] names = new String [5] {"AA", "BB", "CC "}

Int I = new int [10];

Int I = new int [];

      Note: whether it is dynamic or static initialization, you must specify the length of the array during creation;

  3. array reference:

1. the array cursor is referenced. The cursor starts from 0 to n-1, where n is the length of the array.

2. The length of an array is called by the length attribute;

Code

3. How to traverse Arrays: traverse through Loops

For (int I = 0, I <scores1.length; I ++ ){

System. out. println (scores1 [I]);

}

Code display:

1 public class TestArray {2 public static void main (String [] args) {3 int i1; 4 i1 = 12; 5 boolean B = true; 6 // 1. how to define an array 7 // 1.1 Declaration 8 String [] names; 9 int [] scores; 10 // 1.2 initialize 11 // first: static initialization: initialize the array and assign values to the array element at the same time. 12 names = new String [] {"Zhang San", "Li Si", "Wang Wu"}; 13 // type 2: Dynamic initialization: initialize the array and assign values to the array element separately. 14 scores = new int [4]; 15 // 2. how to call the corresponding array element: it is called by using the array element cursor. 16 // The sequence Mark starts from 0 and ends with n-1. N indicates the length of the array. 17 scores [0] = 87; 18 scores [1] = 89; 19 scores [3] = 98; 20 // 3. Array length: The length attribute of the array. 21 System. out. println (names. length); 22 System. out. println (scores. length); 23 // 4. how to traverse array elements 24 // System. out. println (names [0]); 25 // System. out. println (names [1]); 26 // System. out. println (names [2]); 27 for (int I = 0; I <names. length; I ++) {28 System. out. println (names [I]); 29} 30} 31}

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.