Day16 (Java method)

method

1. What is the method

What is the method?

System.out.println()  

system is a class. out is an output object in the class. println () is a method of the object

The meaning of this statement is to call the println method in the standard output object out of the system class

Java methods are collections of statements that together perform a function

Method is an ordered combination of steps to solve a class of problems

Method is contained in a class or object

Methods are created in the program and referenced elsewhere

Principle of design method: the original intention of the method is fast function, which is a collection of fast statements to realize a function. When designing methods, we'd better keep the atomicity of methods, that is, a method only completes one function, which is conducive to our later expansion

Naming rules for methods:

package com.ziyu.method;

public class Demo01 {
    //main method 
    public static void main(String[] args) { //The piblic static modifier void returns the value type
        int sum = add(1, 2); //The add method can only be called below the method
        System.out.println(sum);

    }
    //addition
    public static int add(int a, int b){ //a. B here, only formal parameters are used to give actual parameters
        return a+b;

    }

}

IDEA really fragrant debug mode

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-6ck8wucg-1641901822614) (D: \ javanotebooks \ jietu \ 36)]

By calling the method sum we set, we directly jump to our method. After running, the result is copied to

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG muvroeiu-1641901822615) (D: \ javanotebooks \ jietu \ 37)]

package com.ziyu.method;

public class Demo01 {
    public static void main(String[] args) {
        //int sum = add(1, 2);
        //System.out.println(sum);

        test();//The main method is concise and clean. Some functions are written externally
    }
    public static int add(int a,int b){ //A method performs only one function
        return a+b;
    }
    public static void test(){//void is empty
        for (int i = 0; i <= 1000; i++) {
            if (i%5 == 0){
                System.out.print(i+"\t");
            }
            if (i%(5*3) == 0){ //The last one in each line must be divided by 15, so three lines will be wrapped at this time
                System.out.println();
                //System.out.print("\n");

                //println output wrap
                //print output does not wrap
            }
        }
    }
}

2. Method definition and call

Definition of method

java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following statements

Method contains a method header and a method body. Here are all parts of a method:

Modifier: modifier, which is optional, tells the compiler how to call the method and defines the access type of the method.

Return value type: the method may return a value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void

Method name: is the actual name of the method. The method name and parameter table together constitute the method signature.

Parameter type: the parameter is like a placeholder. When the method is called, the value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters.

Formal parameter: the user receives external input data when the method is called.

Argument: the data actually passed to the method when the method is called

Method body: the method body contains specific statements that define the function of the method

Modifier return value type method name (parameter type parameter name){
   ...
   Method body
   ...
   return Return value
}

If there is a return value, there must be a return void

Method call

Calling method: object name Method name (argument list)

java supports two methods of calling methods, which can be selected according to the return of the method.

When a method returns a value, the method call is usually treated as a value. For example:

int larger = max(30,40)

If the return value of the method is void, the method call must be a statement.

System.out.println("Hello,ziyu")

Value passing (java) and reference passing: https://blog.csdn.net/weixin_34008784/article/details/92427583?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164179208516780255287216%2522%252C%2522scm%2522%253A%252220140713.130102334 …%2522%257D&request_ id=164179208516780255287216&biz_ id=0&utm_ medium=distribute. pc_ search_ result. none-task-blog-2allsobaiduend~default-3-92427583. first_ rank_ v2_ pc_ rank_ v29&utm_ term=%E4%BB%80%E4%B9%88%E6%98%AF%E5%80%BC%E4%BC%A0%E9%80%92&spm=1018.2226.3001.4187

package com.ziyu.method;

public class Demo02 {
    public static void main(String[] args) {

        int test1 = max(20,20);
        System.out.println(test1);//Method has no return value, so it is a statement

    }
    public static int max(int num1,int num2){//Define max method ratio size
        int result = 0;//Defining variables and assigning initial values
        if (num1==num2){
            System.out.println("num1==num2");
            return 0;//return is used to terminate the method. The program should be rigorous. Modifying someone else's program requires someone else's recognition
        }
        if(num1>num2){
            result = num1;
        }else{
            result = num2;
        }
        return result;

    }
}

If

int test = max(20,20);

Become

double test = max(20.0,20.0);

This also needs to compare the size

Method overloading is used when

3. Method overloading

Overloading means that in a class, functions with the same function name but different formal parameters can have the same or different return value types

Rules for overloaded methods:

Method names must be the same.

The parameter list must be different (different number, different type, different parameter order)

The return value types of methods can be the same or different

Just different return types are not enough to overload methods

Implementation theory:

If the method names are the same, the compiler will match them one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error

package com.ziyu.method;

public class Demo02 {
    public static void main(String[] args) {

        double test1 = max(20.0,20.0);
        System.out.println(test1);//Method has no return value, so it is a statement

    }
    //Overloading means that in a class, functions with the same function name but different formal parameters can have the same or different return value types
    public static double max(double num1,double num2){//Define the double type under the max method overload than the size double method overload
        int result = 0;//Defining variables and assigning initial values
        if (num1==num2){
            System.out.println("num1==num2");
            return 0;//return is used to terminate the method. The program should be rigorous. Modifying someone else's program requires someone else's recognition
        }
        if(num1>num2){
            result = (int)num1;
        }else{
            result = (int)num2;
        }
        return result;

    } public static int max(int num1,int num2){//Define max method ratio size
        int result = 0;//Defining variables and assigning initial values
        if (num1==num2){
            System.out.println("num1==num2");
            return 0;//return is used to terminate the method. The program should be rigorous. Modifying someone else's program requires someone else's recognition
        }
        if(num1>num2){
            result = num1;
        }else{
            result = num2;
        }
        return result;

    }
}

4. Command line parameters

Sometimes you want to pass a message to a program when it runs, which depends on passing command-line parameters to the main () function.

public class Commandline{
    public static void main(String args[]){
        for(int i=0;i<args.length;i++){
            System.out.println("args[" + i + "]: "+ args[i]);
        }
    }
}

package com.ziyu.method;

public class Demo03 {
    public static void main(String[] args) {
        //args.length array length
        for (int i = 0; i < args.length; i++) {
            System.out.println("args[" + i +"]: "+ args[i]);

        }
    }
}

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kOC4wA7C-1641901822615)(D:\Javanotebooks\jietu)]

Then enter cmd to the command line corresponding to the path in the folder

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gFn0892L-1641901822616)(D:\Javanotebooks\jietu.png)]

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-V39spZui-1641901822616)(D:\Javanotebooks\jietu.png)]

To run the class file, you need to go back to the root directory file

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ZnG06BU0-1641901822616)(D:\Javanotebooks\jietu.png)]

The run is followed by parameters such as utf-8

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-f3OT51rU-1641901822616)(D:\Javanotebooks\jietu.png)]

5. Variable parameters

public void method(){}
public void method(int i){}
public void method(int i,int n){}
public void method(int i,double o){}

There may be many appeal parameters, and the request is cumbersome when there are more and more parameters, so there are variable parameters

Starting from JDK1... 5, java supports passing variable parameters of the same type to a method.

In a method declaration, add an ellipsis after specifying the parameter type

Only one variable parameter can be specified in a method. It must be the last parameter of the method. Any ordinary parameter must be declared before it.

package com.ziyu.method;

public class Demo04 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();//Demo04 is the current new Demo04(); alt + enter and Demo04 is the object
        demo04.test();//Object Method is called
    }
    public void test(int... i){
        System.out.println(i);
    }
}

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-LoYXXiU2-1641901822617)(D:\Javanotebooks\jietu.png)]

package com.ziyu.method;

public class Demo04 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();//Demo04 is the current new Demo04(); alt + enter and Demo04 is the object
        demo04.test(1,2,3,4,5,6);//Object Method is called
    }
    public void test(int... i){
        System.out.println(i[0]);
        System.out.println(i[1]);
        System.out.println(i[2]);
        System.out.println(i[3]);
    }
}

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-pkq9u9He-1641901822617)(D:\Javanotebooks\jietu.png)]

Variable parameters must be passed on the last parameter

6. Recursion (only available when the cardinality is small)

Method A calls method B, which is easy to understand

Recursion is A method calling A method! Is to call yourself

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-QIaIzfrI-1641901822617)(D:\Javanotebooks\jietu.png)]

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-CJ0ITDv8-1641901822618)(D:\Javanotebooks\jietu.png)]

Using recursion, we can use simple programs to solve some complex problems. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem. The recursion strategy only needs a small number of programs to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code of the program. The ability of recursion is to define an infinite set of objects with finite statements

The recursive structure consists of two parts:

Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle.

Recursive body: when to call its own method.

Recursion must have a recursion exit (termination condition), otherwise it will lead to stack overflow

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-APMlGmP1-1641901822618)(D:\Javanotebooks\jietu.png)]

Boundary conditions: boundary

Previous stage:

Return phase

Stack stage

package com.ziyu.method;

public class Demo06 {
    public static void main(String[] args) {
        System.out.println(f(5));
    }
    //1! 1
    //2! 2*1
    //5!=5*4*3*2*1

    //f=2  2*f(2-1)
    //f=3  3*f(2)=3*f(2*f(1))
    public static int f(int n){
        if (n==1){
            return 1;//Terminate output
        }else{
            return n*f(n-1);
        }

    }
}

The main method is to pop the stack and disappear after the stack pressing is completed

Recursion is very performance consuming

7. Operation:

Write a calculator, which is required to realize the function of addition, subtraction, multiplication and division, and can receive new data circularly, which can be realized through user interaction

Recommended ideas:

Write four methods: addition, subtraction, multiplication and division

User interaction using loop + switch

Pass two numbers that require an operation

Output results

Code reference source: https://blog.csdn.net/Aynaner/article/details/121256525?spm=1001.2014.3001.5501

Slightly modified

package com.ziyu.method;

import java.util.Scanner;

public class test {
    //Write a simple calculator
    public static void main(String[] args) {
        method();//Method method usage
        while(true){
            Scanner scanner = new Scanner(System.in);
            System.out.print("Exit use Q,Continue using input Y ");
            String str = scanner.nextLine();//Receive user input Q/Y
            if (str.equals("Y")){
                method();
            }else if (str.equals("Q")){
                System.out.println("Program end");
                System.out.println(0);
                scanner.close();//The close of scanner must be closed
            }else {
                System.out.print("Input error!!! Please re-enter!!!");
            }
        }

    }
    public static void method(){
        Scanner scanner =new Scanner(System.in);//For receiving user input
        System.out.print("Please enter the first number: ");
        float numb1 = scanner.nextFloat();//Store the user's first input in numb1
        System.out.print("Supported operators:+,-,*,/,^");
        System.out.print("Please enter operator: ");
        String operator = scanner.next();//Operator to receive user input
        System.out.print("Please enter the second number: ");
        float numb2= scanner.nextFloat();//The second input that receives user input is stored in numb2
        switch (operator){
            case "+":
                add(numb1,numb2);//add method use
                break;
            case "-":
                subtract(numb1,numb2);
                break;
            case "*":
                multiply(numb1,numb2);
                break;
            case "/":
                divide(numb1,numb2);
                break;
            case "^":
                power(numb1,numb2);
                break;
            default:
                System.out.println("*****Input error****");
        }
    }
    public static void add(float a,float b){//add method for addition
        System.out.println(a+b);
    }
    public static void subtract(float a,float b){//subtract method for subtraction
        System.out.println(a-b);
    }
    public static void multiply(float a,float b){//Multiply with multiply method
        System.out.println(a*b);
    }
    public static void divide(float a,float b){//divide method for division procedure. The division divisor cannot be 0
        if (b==0){
            System.out.println("Divisor b Cannot be 0");
        }else {
            System.out.println(a/b);
        }
    }
    public static void power(float a, float b){//Factorization by power method
        double end =Math.pow(a,b);
        System.out.println(end);

    }

}

Keywords: Java intellij-idea

Added by Eddyon on Tue, 11 Jan 2022 13:59:51 +0200