loop
Dead cycle
- for loop: execution efficiency takes precedence over while
for (;;) { Loop body statement; }
- while loop: more readable code
while (true) { Loop body statement; }
loop nesting
-
Buy a hundred chickens for a hundred dollars:
Spend 100 Wen to buy 100 chickens, 5 Wen for a rooster, 3 Wen for a hen and 3 Wen for a chick. Spend 100 Wen to buy 100 chickens
public class BasicDemo03 { public static void main (String[] args) { /* Number of cycles = 101 * 101 * 101 = 1030301 for (int gong = 0; gong <= 100 ; gong++ ) { for (int mu = 0; mu <= 100; mu++) { for (int xiao = 0; xiao <= 100 ; xiao++ ) { if ((gong + mu + xiao == 100) && (gong * 5 + mu * 3 + xiao / 3 == 100) && (xiao % 3 == 0)) { System.out.println("There are "+ gong +" cocks, "+ mu +" hens and "+ xiao +" chicks); } } } } */ /* //Number of cycles = 21 * 34 * 101 = 72114 for (int gong = 0; gong <= 20 ; gong++ ) { for (int mu = 0; mu <= 33; mu++) { for (int xiao = 0; xiao <= 100 ; xiao++ ) { if ((gong + mu + xiao == 100) && (gong * 5 + mu * 3 + xiao / 3 == 100) && (xiao % 3 == 0)) { System.out.println("There are "+ gong +" cocks, "+ mu +" hens and "+ xiao +" chicks); } } } } */ //Number of cycles = 21 * 34 = 714 for (int gong = 0; gong <= 20 ; gong++ ) { for (int mu = 0; mu <= 33; mu++) { int xiao = 100 - gong - mu;//If it's divided by three if ((gong * 5 + mu * 3 + xiao / 3 == 100) && (xiao % 3 == 0)) { System.out.println("The cock has"+gong+"Only, the hen has"+mu+"Chicken, chicken"+xiao+"only"); } } } } }
- Print all prime numbers between 1-100:
/* Exercise: print all prime numbers between 1-100 Prime number: a number that can only be divided by 1 or itself. 1 is not a prime number Features: there are 2 factors Divisor / divisor = quotient remainder Execution process 1 / 1 = 1 ...... 0 2 / 1 = 2 ...... 0 2 / 2 = 1 ...... 0 3 / 1 = 3 ...... 0 3 / 2 = 1 ...... 1 3 / 3 = 1 ...... 0 4 / 1 = 4 ...... 0 4 / 2 = 2 ...... 0 4 / 3 = 1 ...... 1 4 / 4 = 1 ...... 0 ....... Above analysis: Outer loop: divisor Inner loop: divisor */ public class BasicDemo04 { public static void main (String[] args) { int c = 0; /* for (int i = 1; i <= 100 ; i++ ) { //Declare a counter variable that initializes the number of divisions int count = 0; for (int j = 1; j <= i; j++) { c++; if (i % j == 0) { count++; } } if (count == 2) { System.out.println(i); } } System.out.println(c);//5050 */ //Number of cycles: 1133 for (int i = 2; i <= 100 ; i++ ) { //Set a flag for each divisor. By default, all integers are prime numbers boolean flag = true; for (int j = 2; j < i; j++) { c++; if (i % j == 0) { flag = false; break; } } if (flag) { System.out.println(i); } } System.out.println(c); } }
- Print 99 multiplication table:
/* 99 multiplication table outer loop: rows Inner loop: columns */ public class BasicDemo05 { public static void main (String[] args) { for (int hang = 1; hang <= 9; hang++) { for (int lie = 1; lie <= hang ; lie++ ) { System.out.print(lie + "*" + hang + "=" + hang * lie + "\t"); } System.out.println(); } } }
method
definition
method is a code block that performs special functions
benefit
- Improve the reusability of code, so as to improve the development efficiency
- Extract the functional code to effectively reduce the coupling of code (reduce the dependence between code and code)
Declaration format
Modifier public static return value type method name (parameter type 1, parameter name 1, parameter type 2, parameter name 2,...){
Method body statement
Return return value// If there is a return value, it will be returned to the caller. If there is no return value, the method will be ended by return
}
Method and return
- Parameter passing: caller method = = Data > custom method
- Return: custom method = = result > caller method
Two clear before the statement
-
Return value type:
- Basic data type
- Reference data type
- no return value
-
Formal parameter list:
- Several data in the caller method are required
- Data type and variable name for each data type
Method characteristics
No call, no execution
Method calling method (3 * 3)
-
If the method belongs to a class, the calling method:
Class name Method name (argument); -
If the method belongs to an object, the calling method is:
Object name Method name (argument);
(the above categories and objects are not learned)
-
If you call a method in the same class:
- Individual call (direct call)
Method name (argument); - Output call (print call)
System. out. Println (method name (argument)); - Assignment call
Data type variable name = method name (argument);
- Individual call (direct call)
Call example: complete the summation calculation of two integers through the method
- code
public class MethodDemo02 { public static void main (String[] args) { //Individual call (direct call) //getSum(3,4); //Output call //System.out.println(getSum(3,4)); //Assignment call int sum = getSum(3,4); System.out.println(sum); } /* Two clear: Return value type: int Formal parameter list: int a, int b */ public static int getSum (int a , int b) { int sum = a + b; return sum; } }
- Memory diagram of method call
void keyword
- When declaring a method, if the method does not have a return value, the position of the return value type cannot be empty. You need to use the void keyword to occupy the position (void means that the method has no return value)
- When the return value type of the method is void, the calling method can only be called separately, otherwise the compilation will report an error
- When the return value type of the method is void, the return statement can be omitted
Example: print HelloWorld for a specified number of times
*/ public class MethodDemo05 { public static void main (String[] args) { print(10); } /* Two clear: Return value type: void Formal parameter list: int num */ public static void print (int num) { for (int i = 1; i <= num ; i++ ) { System.out.println("HelloWorld"); } return; //System. out. println("111111"); You can't write code after return. Return ends the method } }
Overloading of methods
Method overloading: in the same class (or in the inheritance relationship between child and parent classes), the method name is the same and the formal parameter list is different
- Precautions for method overloading:
Precautions for method overloading:
1. Must be in the same class (or in the inheritance relationship of child and parent classes)
2. The method name must be the same
3. The formal parameter list must be different (at least one of the following must be met)
a. The number of formal parameters is different
b. The data types of formal parameters are different
c. The order of formal parameter data types is different
4. The call of overloaded method depends on the actual parameters when calling the method, and the appropriate method is matched according to the actual parameters
- Method overload exercise
public class MethodDemo07 { public static void main (String[] args) { method(123); /*The result is int; If the argument is changed to cast (byte)123 and the byte method is removed at the same time, according to the content of day02: when byte, short and char participate in mathematical operation, the result will automatically skip the level to int. there is no mathematical operation here, so the data type of the argument is promoted from byte to short, the short method will be matched, and short will be output after calling the short method */ //method(3,4);//A int double B double int / / the virtual machine does not know whether to increase by 3 or 4. An error is reported //System.out.println(null);// Unclear quotation and error reporting, the same as above } public static void method (int a , double b) { System.out.println("int double"); } public static void method (double a, int b) { System.out.println("double int"); } /* public static void method (int a , int b) { System.out.println("int int"); } public static void method (double a, double b) { System.out.println("double double"); } */ //For the above two methods, if the argument is (3,4.5), double double is output public static void method (byte num) { System.out.println("byte"); } public static void method (short num) { System.out.println("short"); } public static void method (int num) { System.out.println("int"); } public static void method (long num) { System.out.println("long"); } }
Summary of methods
1. Location of method declaration: in class, outside method; Nesting of methods cannot be formed in a program
2. When declaring a method, if the return value type is not available, it cannot be empty. You need to use the void keyword to replace it
3. When the return value type of the method is void, the return keyword in the method can be omitted
4. There can be multiple return statements in a method, but only one is executed in the end
5. When the return value type of a method is void, the method can only be called individually (directly)
When the return value type of the method is not void, it is recommended to use assignment call
6. Method can have no formal parameters
Recursion of method
Recursion of method: a phenomenon that the method itself calls itself in the program
recursive partitioning
- Direct recursion: the method itself calls itself
- Indirect recursion: method A calls method B, method B calls method C, and method C calls method A
Prerequisites for using recursion
Using recursion must add an end condition to it, otherwise it will cause stack memory overflow
The number of layers of recursion cannot be too many. Even adding an end condition will lead to stack memory overflow
Benefits of recursion
It can help us solve some problems that cannot be solved by using circular statements
For example:
Operate multi-level folders
Pseudo code:
public static void getPath (path){
Get all files and folders in the current path
Traversing the acquired container if (Is it a file) { Print file path } else { Print folder path getPath(New path); } }
- Find the cumulative sum before 1 to the specified number
public class MethodDemo10 { public static void main (String[] args) { int sum = getSum(5); System.out.println("sum = " + sum); } /* Two clear: Return value type: int Formal parameter list: int num */ public static int getSum (int num) { if (num == 1) { return 1; } return num + getSum(num - 1); } public static int add (int num) { int sum = 0; for (int i = 1 ; i <= num ; i++ ) { sum += i; } return sum; } }
Code execution diagram
Disadvantages of recursion: Fibonacci sequence
- Requirements:
There is a pair of rabbits. They give birth to a pair of rabbits every month from the third month after birth. The little rabbit grows to another pair of rabbits every month after the third month. If the rabbits don't die, what are the logarithm of rabbits in the specified month?
law:
First month: 1
Second month: 1
The third month: 2
Fourth month: 3
Fifth month: 5
Sixth month: 8
...
Rule: from the third month, the rabbit logarithm of each month is the sum of the rabbit logarithm of the first two months, and the rabbit logarithm of the first and second months is 1
- code
public class MethodDemo11 { //A variable that declares the number of method calls static long count = 0; public static void main (String[] args) { //Get the time in nanoseconds at this time. 1 second = 1000 milliseconds, 1 millisecond = 1000 microseconds, 1 microsecond = 1000 nanoseconds long start = System.nanoTime(); long num = getNum02(50); //Gets the time in nanoseconds at this time long end = System.nanoTime(); System.out.println("Total logarithm of rabbits:" + num); System.out.println("Number of method calls:" + count); System.out.println("Program running time:" + (end - start)); } /* Two clear: Return value type: long Parameter list: int month */ /* Total number of rabbits: 12586269025 Number of method calls: 1 Program running time: 8796 */ // dynamic programming public static long getNum02 (int month) { count++; //Logarithm of the current month long temp = 0; //Logarithm of rabbits last month long a = 1; //Logarithm of rabbits last month long b = 1; if (month == 1 || month == 2) { return 1; } for (int i = 3; i <= month ; i++) { temp = a + b; b = a; a = temp; } return temp; } /* Total number of rabbits: 125.8626.9025 Number of method calls: 251.7253.8049 Program running time: 63784380668 */ public static long getNum01 (int month) { count++; if (month == 1 || month == 2) { return 1; } return getNum01(month - 1) + getNum01(month - 2); } }