Java basics 2
Program flow control-sequence structure
Sequence structure: the program is executed line by line from top to bottom, without any judgment or jump in the middle
Program flow control-branch structure
According to conditions, selectively execute a certain piece of code (if.....else and switch statements)
Branch structure 1: if statement
Three forms of if statement: 1. if(true) {execute code block;} 2. if (conditional expression) {execute code block;} else {execute code block;} 3. if (conditional expression) {execute code Block;} else if (conditional expression) {execute code block;}.... else{execute code block;}
Practice if statement:
public static void main(String[] args){ /** * Determine Xiao Ming’s final score int score = 90; if(score == 100) { System.out.println("Reward a BWM"); } else if (score> 80 && score <=90) { System.out.println("An iPhone5s"); } else if (score >= 60 && score <= 80) { System.out.println("A reference book "); } else { System.out.println("Nothing"); } */ /*For the following codes, if there is output, indicate the input result*/ int a = 4; int y = 1; if( a> 2 ){ if(y> 2){ System.out.println (a + y); System.out.println("atguigu"); } } else { System.out.println("x is " + a); } }
Molecular structure 2: switch statement
switch (variable) { case constant 1: statement 1; break; case constant 2: statement 2; break; ...... case constant N: statement N; break; default: statement 2; break; }
Switch statement exercise
public static void main(String[] args ){ //例子 int i = 123; switch (i) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.err.println("two"); break; default: System.out.println("default"); break; } /*输入季节,输出季节特色 */ String season = "abc"; switch(season){ case "spring": System.out.println("春暖花开"); break; case "summer": System.out.println("Summer Inflammation"); break; case "autumn": System.out.println("Autumn high and cool"); break; case "winter": System.out.println(" Winter snowy") ; break; default: System.out.println("The season input is wrong! Please re-enter:"); break; } }
note:
-
The return value of the expression in switch (expression) must be one of the following types: byte, short, char, int, enumeration, String;
-
The value in the case clause must be constant, and the values in all case clauses should be different;
-
The default clause is optional. When there is no matching case, default is executed;
-
The break statement is used to make the program jump out of the switch statement after executing a case branch; if there is no break, the program will execute sequentially to the end of the switch;
Comparison of switch statement and if statement
-
If the specific value to be judged is not many, and it conforms to byte, short, int, char, although both statements can be used, it is recommended to use the switch statement because of high efficiency;
-
Other situations: judge the interval, judge the result of Boolean type, use if, and the scope of use of if is wider;
Program flow control-loop structure
Loop statement function: the function of repeatedly executing specific codes when certain conditions are met;
The four components of the loop statement:
-
Initialization part
-
Loop condition part
-
Loop body part
-
Iterative part
Classification of loop statements:
-
for loop
-
while loop
-
do while loop
for loop statement
Syntax format: for (initialization expression; Boolean test expression; change expression) {statement or statement block}
例子: for(int i = 1;i < 10;i++){ System.out.println(i); }
for statement practice
public static void main(String[] agrs){ /**Write the program FooBizBaz.java, loop from 1 to 150 and print a value on each line, * In addition, print out "foo" on each line that is multiple of 3, in Print "biz" on each line of multiples of 5, * print out "baz" on each line of multiples of 7. for(int i = 1;i <151;i++){ String str = ""; str += i; if(i% 3 == 0){ str += "foo"; } if(i% 5 == 0) { STR + = "BIZ"; } IF (I == 0. 7%) { STR + = "baz"; } System.out.println (STR); } * / / ** // calculation 1- -100 sum int a = 0; for(int i = 1;i <101;i++){ a += i; } System.out.println(a); */ /*Print the sum of all odd numbers between 1~100 int r = 0; for(int i = 1;i <101;i++){ if( i% 2 != 0){ r += i; } } System.out.println(r); */ /** * Print the number and sum of all integers between 1 and 100 that are multiples of 7 (experience The idea of setting the counter) int y = 0; int res = 0; for(int i = 1;i <= 100;i++){ if(i% 7 == 0){ y++; res += i; } } System .out.println(y); System.out.println(res); */ }
while loop
Syntax: initialization statement; the while (Boolean expression test) { statements or statement blocks; change statements (i ++ or the like); } example: public static void main (String args []) { int Result = 0; int I . 1 =; the while (I <= 100) { Result + = I; I ++; } System.out.println ( "Result =" + Result); }
do while loop statement
Syntax format: initialization statement; do{ statement or statement block; change statement (i++ and the like); }while (Boolean test expression); example: public static void main(String args[]){ int result = 0, i . 1 =; do { Result + = I; I ++; } the while (I <= 100); System.out.println ( "Result =" + Result); }
The difference between the three loop statements
public static void main(String args[]){ /**Find the sum of all even numbers between 1 and 100 to express the statement in three loops * for loop int res = 0; for(int i = 1;i <101;i++ ){ if(i% 2 == 0){ res += i; } } System.out.println(res); //while statement loop int i = 0; int res = 0; while(i <101){ if(i% 2 == 0){ res += i; } i++; } System.out.println(res); //do-while loop int res = 0; int i = 0; do{ if (i% 2 == 0){ res += i; } i++; }while(i <101); System.out.println(res); */ }
Nested loop
-
Putting a loop inside another loop forms a nested loop. Among them: for, while, do..while can be used as outer loop and inner loop;
-
In essence, the nested loop is to treat the inner loop as the loop body of the outer loop. When only the loop body of the inner loop is false, it will completely jump out of the loop body and end the current loop of the outer loop and start The next cycle
-
Assuming that the number of the outer loop is m times, and the inner loop is n times, the inner loop body actually needs to be executed m*n times
Example: public static void main(String args[]){ //Print 9*9 multiplication table for(int i =1;i <= 9; i++){ for(int j = 1;j <= i;j++) { System.out.print(j + "*" + i + "=" +(i * j)+"\t"); } System.out.println(); } /* //Print 1--100 Prime number between (prime number: a natural number greater than 1 and only divisible by 1 and itself) for(int i = 1;i <101;i++){ int m =0; for(int j = 1; j <= i ;j++){ if(i% j == 0){ m++; } } if(m == 2){ System.out.println(i); } } */ }
Special flow control statement
-
Break statement: Terminate the current loop (end the loop)
-
continue statement: terminate the current loop and enter the next loop
-
return: end a method (when a method is executed to a return statement, the method will be ended)
Note: return directly ends the entire method, no matter how many levels of loop this method return is in, it will be ended;
example
public static void main(String args[]){ /**Special flow control statement * break statement: used to terminate the current loop (end the current loop); * continue: used to end the current loop, directly enter the next One loop * return: end a method, when a method executes to a return statement, this method ends * Note: break--can only be used for switch statements and loop statements * continue--can only be used for loop statements * */ //Nested loop System.out.println("complete loop result"); for(int i = 1;i <5;i++){ for(int j = 1;j <4;j++){ System.out .print(i); //print(): the input result does not automatically wrap System.out.print(j); //println(): the input result automatically wraps System.out.println(); } } System.out. println(); System.out.println(); //break: terminate the current loop System.out.println("test break statement: end the current loop"); for(int i = 1;i <5;i++){ for(int j = 1;j <4;j++){ if(j == 2){ break; } System.out.print(i); System. out.print(j); System.out.println(); } } System.out.println(); System.out.println(); //continue: end this cycle and enter the next cycle System.out. println("Test continue statement: end this loop and enter the next loop"); for(int i = 1;i <5;i++){ for(int j = 1;j <4;j++){ if(j == 2){ continue; } System.out.print(i); System.out.print(j); System.out.println(); } } System.out.println(); System.out.println(); //return: termination method System.out.println("Test the return statement: terminate this method directly"); for(int i = 1;i <5;i++){ for(int j = 1;j <4 ;j++){ if(j == 2){ return; } System.out.print(i); System.out.print(j); System.out.println(); } } }
##
One-dimensional array
Declaration method: type var[] or type[] var;
One-dimensional array initialization :
-
Dynamic initialization: the operation of array declaration and allocating space for array elements and assignment is carried out separately, such as: int arr[] = new int[10];
-
Static initialization: When defining the array, allocate space and assign values to the array elements, such as: int a[] = new int[]{1,2,3,4}
Array reference
-
After defining and using the operator new to allocate space for it, each element in the array can be referenced;
-
Reference method of array elements: array name [array element subscript] (array element subscript can be an integer constant or an integer expression; the array element subscript starts from 0)
-
Each array has an attribute length indicating its length
-
Once the array is initialized, its length is immutable
public static void main(String[] agrs){ /** * Array--a collection of multiple data*/ //One-dimensional array int a[]; int[] b; int arr[] = new int[5 ];//Dynamic assignment int[] arr1 =new int[]{1,2,3,4,5};//Static assignment //Array subscript starts from 0 System.out.println(arr.length); System.out.println(arr1[1]); System.out.println(arr1[1*2]); System.out.println(arr[1]); }
Multidimensional Arrays
Two-dimensional array : the array in the array
Format (dynamic initialization) 1: int [] [] arr = new int [3] [2]; (three one-dimensional arrays, each one-dimensional array has two elements)
Format (dynamic initialization) 2: int [] [] arr = new int [3] [];
Format (static initialization) 3: int[] [] arr = new int [] []{ {1,2,3}, {2,7}, {1,2,3}};
public static void main(String[] args){ int[][] arr = new int[][]{ {3,8,2}, {2,7}, {9,0,1,6} }; int len = arr.length; int res = 0; for(int i = 0; i < len; i++){ int arr0[] = arr[i]; int llen = arr0.length; for(int j = 0;j < llen;j++){ res +=arr0[j]; } } System.out.println(res); }
Array exercises
public static void main(String[] agrs){ /** * Common algorithms involved in arrays * 1. Find the maximum, minimum, sum, and average of array elements */ int arr[] = new int[] {1,2,3,4,5,6,7,8 }; int max = arr[0]; int min = arr[0]; int sum = 0; int avg; int i; for( i = 0 ;i <arr.length;i++){ if(max <arr[i]){ max = arr[i]; } } System.out.println("Maximum:"+max); for(int j = 0 ; j <arr.length;j++){ if(min> arr[j]){ min = arr[j]; } } System.out.println("minimum value:"+min); //sum, average for(int k = 0;k <arr.length; k++){ sum +=arr[k]; } System.out.println("总和:"+sum); System.out.println("平均数:" + (sum / arr.length)); //2、数组的复制 int copy[] =new int[arr.length]; for(i = 0; i < arr.length;i++){ copy[i] = arr[i]; } for(i = 0;i < copy.length;i++){ System.out.println(copy[i]); } System.out.println(); System.out.println(); //3、数组的反转 int temp[] = new int[arr.length]; int k =0; for(i = arr.length - 1;i >= 0;i--){ //System.out.println(arr[i]); temp[k] = arr[i]; k++; } arr = temp; for(i = 0;i < arr.length;i++){ System.out.println(arr[i]); } }
Bubble Sort
public static void main(String[] args){ */ /**4. Sorting bubble method of array elements : sorting idea: compare two adjacent elements, exchange if necessary, and the maximum value will be the largest after completing a loop The elements are ranked last (such as sorting from small to large), the next cycle is to perform similar operations on other numbers */ int arr[] = new int[]{10,32,1,234,554,6,21}; int temp; for (int i = 0;i <arr.length-1; i++){//Loop rounds for(int j = 0; j <arr.length-1-i ;j++){//Every round, yes Array elements are sorted if(arr[j]> arr[j + 1]){ temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for (int i = 0;i <arr.length;i++){ System.out.println(arr[i]); } }