Nested and recursive Java method calls

EDITORIAL: bloggers is to join the training career after a battle-development experience "boars", a nickname taken from the animated film "The Lion King" in the "Peng Peng", always optimistic and positive attitude towards the surrounding thing. Technical route from my full-stack Java engineer all the way toward the development of big data, data mining, and now finally have small achievements, is willing to exchange 5012 we acquired the former, you want to learn the way of help. At the same time, the bloggers also want to try to create a complete technical library, any articles related to the technical point exceptions, error, precautions are listed at the end, welcome to provide material in various ways.

  • For any errors that appear in the article please critics pointed out, must be revised.
  • Have any questions you want to discuss and study can contact me: [email protected].
  • Publish the article because of the style column-specific, self-contained and inadequacies please correct me.

Nested and recursive Java method calls

This article Keywords: method, nesting, recursion, classical problems

A nest, the method

1. Interpretation of the concept

In fact, the concept of nested method is better understood, is in the process of calling the method has encountered calling methods, although logically can understand why the result is such a run, but for code execution process is still at the beginning of contact some feel around.

2. The method of nesting

In programming, the most common method is to call nesting and methods, because under normal circumstances, we solve a problem does not rely on a method. And if a method is provided so powerful, it is bound to one of the code logic and argument list also become relatively complex, it is not conducive to modify and use, so we hope that each method is a little more cutting edge, with to solve a particular problem, to complete a more complex function by means of a combination, like a knife seven Rennes.
Here Insert Picture Description
For example, we have two methods: are used to calculate the area of a circle and calculate the area of a rectangle, if we now need to calculate the surface area of a cylinder, we also need to rewrite the entire method again? Of course not required, because the calculation of the surface area of the cylinder just to the side area (rectangle) is obtained by two cylindrical bottom area (circle) plus cylinder, we only need a reasonable incoming parameters and return values can be realized.

public class Test{
    public static void main(String[] args){
        // 计算一个圆柱的面积,已知底面半径和高
        int radius = 5;
        int height = 10;
        // 调用计算圆柱表面积
        double area = getColumnArea(radius,height);
        // 输出结果
        System.out.println("圆柱的表面积为:" + area);
    }
    public static double getCircleArea(double radius){
        // 根据圆的半径计算面积后返回
        return Math.PI * Math.pow(radius,2);
    }
    public static double getRectangleArea(double width,double height){
        // 根据宽和高计算面积后返回
        return width * height;
    }
    public static double getColumnArea(double radius,double height){
        // 计算得到底面积 -> 刚好是侧面积的宽
        double baseArea = getCircleArea(radius);
        // 计算得到侧面积
        double lateralArea = getRectangleArea(baseArea,height);
        // 根据底面积及侧面积计算后返回
        return baseArea * 2 + lateralArea;
    }
}

So, the whole process of the implementation of the method is what is it? In fact, still a sequential structure, a method is invoked when fully implemented will continue in subsequent steps, we can describe this process as follows:
Here Insert Picture Description

3. nest construction

In the previous article has been to introduce the overloaded constructor can be applied to the number of different attributes to initialize Watch Portal: Tools Java initialize the object - constructor . However, the use we find a problem, the main purpose is to constructor property assignment, but will be found in the overloaded constructor, as there is redundant code, there will be as many of the same assignment as obsessive-compulsive disorder patients with severe, this can not be tolerated, see the following example:

public class Person{
    // 一参构造器
    public Person(String name){
        this.name = name;
    }
    // 两参构造器,可以给name和age属性赋值
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    // 三参构造器,可以给name、age和job属性赋值
    public Person(String name,int age,String job){
        this.name = name;
        this.age = age;
        this.job = job;
    }
    public String name;
    public int age;
    public String job;
}

In the above example we have defined three constructors, respectively, to meet the different needs of initialization (of course, we can also define more), but you can find a lot of assignments are repeated, we can call each other by constructor ways to reduce the code amount. In the current class constructor call each other using this () way to complete, fill in brackets the corresponding parameters, the revised code is as follows.

public class Person{
    // 一参构造器
    public Person(String name){
        this.name = name;
    }
    // 两参构造器,可以给name和age属性赋值
    public Person(String name,int age){
        this(name);
        this.age = age;
    }
    // 三参构造器,可以给name、age和job属性赋值
    public Person(String name,int age,String job){
        this(name,age);
        this.job = job;
    }
    public String name;
    public int age;
    public String job;
}

If using a three-parameter in the test class constructor initializes a Person object: Person person = new Person ( "Zhang" 25, "engineer"); perform the procedure is as follows:
Here Insert Picture Description

Recursive Second, the method of

1. Interpretation of the concept

Recursion is a computing process or method, is a similar to break the problem into sub-problems approach to solve the problem, then what is the problem then the same child? It is a big problem for dismantling, and the child's problem is the same rule, or the same kind of operation, such as the simplest factorial. If we need to calculate the factorial of 4, write directly mathematically is 4! = 4 x 3 x 2 x 1.
So how do we solve this problem with the computer it? Of course, we can use cycle, from the given number has been multiplied by up to 1:

public class Test{
    public static void main(String[] args){
        int n = 4;
        int result = 1;
        for(int i = n;i <= 1;i--){
            result *= i;
        }
        System.out.println(result);
    }
}

But in fact it can be summarized as a rule or decomposed: n = nx (n - 1) !, n ≥ 2; n = 1, n = 1!!. Well, this cycle and what difference does it make? The difference is that when we use the loop, we will own this calculation process is fully translated into computer code that can be read and executed directly, but was not the original meaning, and in some cases, not all problems can be loop structure to achieve. On the other hand, it can prove recursive calculation of the theoretical role can completely replace the cycle, but for performance reasons, we will not deliberately used to replace a recursive loop, and prefer to use recursion to solve a particular kind of problem.

2. Recursive thinking

Can be seen from the above description, we hope that by thinking recursively close to the original as possible description of the problem, and can solve the problem well. From the point of view of the code, the recursive method is summarized in one sentence: to itself . Why do you say? Because the entire process is performed achieved by repeating a step of generating a result for each step are derived from the previous step or before step. The question then comes, and when the head of it? This leads to a concept: recursive exports .
Like circulation need to have as a termination condition, constantly calls itself recursively, to get the results they need, it is also to have a termination condition, the set conditions are usually more obvious, and that is to get an exact result when, do not need to be a recursive call, this time directly to concrete results returned can be, for example, we use a recursive factorial to achieve:

public class Test{
    public static void main(String[] args){
        int n = 4;
        int result = getFactorial(n);
        System.out.println(result);
    }
    // 定义一个方法,用于计算n的阶乘,不考虑n < 0的情况
    public static int getFactorial(int n){
        // 递归的出口
        // 描述当n = 1时,阶乘的结果为1,直接返回确定的结果
        if(n == 1){
            return 1;
        }else{
            // 根据规律,此时应该先获取到n - 1的阶乘的结果
            // 描述当n ≥ 2时,n! = n x (n - 1)!
            return n * getFactorial(n - 1);
        }
    }
}

When we put together a formula or a description of the law, we can try to think in accordance with the following ideas:

  • First need to determine the outlet recursive, that is the condition that is generally outlet: Incoming parameter determination value can be obtained when the value of
  • The next step is to determine the content of exports, that is, when the judgment in line with the conditions, determine the value of the resulting
  • The last part is the recursive call, according to the laws summed up by the expression expression out

3. execution

If you understand this decomposition process, then we have achieved from the code of this description, when n = 1, can directly get the result of determination: 1; when n ≥ 2, by recursive calls (calls itself), the n - 1 as a parameter, on behalf of want to get n - 1 is the value of recursion, the n - 1 after passed, if the result can not be determined, it will continue to call, then the whole operation process by the following chart To represent:
Here Insert Picture Description

4. classic problem

  • Fibonacci number

Fibonacci column is a classic series, the first term is 1, the second term is 1, from the beginning of the third term, the value of each item are the first two and, mathematically tidy way is : when n = 1 or n = 2, f (n) = 1; when n ≥ 3, f (n) = f (n - 1) + f (n - 2). Accordance with the previous steps, we can determine the export n = 1 or n = 2, is determined to obtain a value of: 1, is the portion of the recursive call: f (n - 1) + f (n - 2), whereby the write the program:

public class Test{
    public static void main(String[] args){
        int n = 5;// 自定义一个正整数n
        int result = f(n);
        System.out.println(result);
    }
    public static int f(int n){
        // 递归出口:当n = 1或n = 2时终止调用,得到确定的值
        if(n == 1 || n == 2){
            return 1;
        }else{
            // 自第三项开始,结果为前两项的加和
            return f(n - 1) + f(n - 2);
        }
    }
}
  • Pascal's Triangle

Pascal's Triangle is a very interesting graphics, a fixed value pyramid composition, top and sides is 1, then what you should expect? Yes, recursive exports! Other portions of the upper layer is with its two nearest values and added, such as: top-down (fourth layer, third column), its value (level 3, column 2) + (layer 3, column 3).
Here Insert Picture Description
If we use the variable i represents layer, j represents the column of this layer, then (i, j) value (i - 1, j - 1 ) + (i - 1, j), which is what? Yes, the law of the description! Finally, we just need to get a recursive determination of export conditions, everything is done it! We know from the above composition, the number of elements of each layer, this layer does not exceed the number of layers, and just the same, so you know how the top and sides describe it?

public class Test{
    public static void main(String[] args){
        int i = 4;// 定义一个正整数i
        int j = 3;// 定义一个正整数j,大小不能超过i
        int result = getN(i,j);
        System.out.println(result);
    }
    public static int getN(int i,int j){
        // 第1层和第1列的值固定为1,最后一列的值也固定为1
        if(i == 1 || j == 1 || j == i){
            return 1;
        }else{
            // 使用表达式描述规律
            return getN(i - 1,j - 1) + getN(i - 1,j);
        }
    }
}

That this is over? how come! Since met so beautiful graphics, no printed out how the program can eliminate itch in my heart! And obtain a single value is different when printing is required to enter the number of layers you want to display, then we will use a double for the cycle to build out the entire graphics of:

public class Test{
    public static void main(String[] args){
        int n = 5;// 定义一个正整数n
        print(n);
    }
    public static void print(int n){
        for(int i = 1;i <= n;i ++){
            // 在每行前插入空格,空格数量与目标层数相关
            for (int j = i;j <= n;j++){
                System.out.print(" ");
            }
            for (int j = 1;j <= i;j++){
                // 输出后进行留空
                System.out.print(getN(i,j) + " ");
            }
            // 打印一层后换行
            System.out.println();
        }
    }
    public static int getN(int i,int j){
        // 第1层和第1列的值固定为1,最后一列的值也固定为1
        if(i == 1 || j == 1 || j == i){
            return 1;
        }else{
            // 使用表达式描述规律
            return getN(i - 1,j - 1) + getN(i - 1,j);
        }
    }
}

Results are as follows:

Published 39 original articles · won praise 467 · views 270 000 +

Guess you like

Origin blog.csdn.net/u012039040/article/details/104990849