Java basic syntax: method calling, method overloading, array 1, getting index

Java basic syntax: method calling, method overloading, array 1, getting index

1. Concept

1.1 Concept

Method: The smallest execution unit in the program

Note: Methods must be created before they can be used. This process becomes method definition.
The method cannot be run directly after it is created. It needs to be manually used before execution. This process becomes a method call.

2. Method definition and calling

2.1 Definition and calling of parameterless methods

Method definition:

    public static void 方法名称(){
    
    
        方法体代码;
    }

Note: The method must be defined first and then called, otherwise the program will report an error

Example of parameterless method :
Code example for finding the larger of two numbers :

    public static void main(String[] args) {
    
    
        getMax();
    }

    //定义方法getMax()
    public static void getMax() {
    
    
        int m = 6;
        int n = 9;
        if(m > n) {
    
    
            System.out.println(m);
        } else {
    
    
            System.out.println(n);
        }
    }

Running results :
Insert image description here

2.2 Definition and calling of methods with parameters

(1) Parameters: composed of data type and variable name, such as: int m

public static void 方法名 ([参数类型 形参 ...]) {
    
    
	方法体;
}

public static void 方法名 (参数1, 参数2, ...) {
    
    
	方法体;
}

Note: When defining a method, the data type and variable name in the parameters must be missing. If any one is missing, the program will report an error.
When defining a method, use commas (,) to separate multiple parameters.

Call example :

  isNumber(10);
  getMax(6,9);
  • When a method is called, the number and type of parameters must match the settings in the method definition, otherwise the program will report an error.

(2) Formal parameters and actual parameters

  • Formal parameters: parameters in method definition, equivalent to variable definition format, for example: int n
  • Actual parameters: parameters in method calls, equivalent to using variables or constants, for example: 6 n

Example of method with parameters :
Code example for finding the larger of two numbers :

public static void main(String[] args) {
    
    
        //在main()方法中调用定义好的方法(使用变量)
        int a = 9;
        int b = 6;
        getMax(a, b);
    }

    public static void getMax(int a, int b) {
    
     //为方法定义两个参数,用于接收两个数字
        if(a > b) {
    
    
            System.out.println("a="+a);
        } else {
    
    
            System.out.println("b="+b);
        }
    }

Running results :
Insert image description here

2.3. Definition and calling of methods with return values

(1) Method definition

  public static 数据类型 方法名称 ( 参数 ) {
    
    
      return 数据 ;
  }

Example:

  public static int getMax( int m, int n ) {
    
    
      return  10 ;
  }

Note: When defining a method, the return value after return must match the data type on the method definition, otherwise the program will report an error.

Call format :

方法名 ( 参数 ) ;
数据类型 变量名 = 方法名 ( 参数 ) ;

Example :

isEvenNumber ( 8 ) ;
boolean  flag =  isEvenNumber ( 8); 

Note: The return value of a method is usually received using a variable, otherwise the return value will be meaningless.

(2) Example : Same as above

Code example :

public static void main(String[] args) {
    
    
          //在main()方法中调用定义好的方法并直接打印结果
          System.out.println(getMax(10,20));

          //在main()方法中调用定义好的方法并使用变量保存
          int res = getMax(23,32);
          System.out.println("res="+res);
      }

      public static int getMax(int a, int b) {
    
    
          if(a > b) {
    
    
              return a;
          } else {
    
    
              return b;
          }
      }

Operation results :
Insert image description here
(3) Example: Compare the areas of two circles

Code example :

public static void main(String[] args) {
    
    
        Scanner s = new Scanner(System.in);
        System.out.print("请输入第一个圆的半径:");
        int r1 = s.nextInt();
        System.out.print("请输入第二个圆的半径:");
        int r2 = s.nextInt();

        double area1 = getArea(r1);
        double area2 = getArea(r2);
        if(area1 > area2){
    
    
            System.out.println("第一个圆面积大");
        }else{
    
    
            System.out.println("第二个圆面积大");
        }
    }

    public static double getArea(int r) {
    
    
        double area = 3.14 * r * r;
        return area;
    }

Running results :
Insert image description here

3. Notes on methods

3.1 Methods cannot be nested definitions

(1) Code example:

    public static void main(String[] args) {
    
    
    }

    public static void add() {
    
    
        public static void add() {
    
    
            // 编译错误
        }
    }

Note: void means no return value, return can be omitted, or return can be written separately without adding data after it.

(2) * Code example:

    public static void main(String[] args) {
    
    

    }
    public static void add() {
    
    
        //return 10; 编译错误,因为没有具体返回值类型
        return;
        //System.out.println(10); return语句后面不能跟数据或代码
    }

4. Method overloading

(1) Method overloading: The relationship between multiple methods defined in the same class. Multiple methods that meet the following conditions constitute overloading of each other.

  • Multiple methods in the same class
  • Multiple methods have the same method name
  • The parameters of multiple methods are not the same, of different types or numbers.

Code example :

    public class MethodDemo {
    
    
        public static void ad(int a) {
    
    
            //方法体
        }
        public static int ad(double a) {
    
    
            //方法体
        }
    }

    public class MethodDemo {
    
    
        public static float ad(int a) {
    
    
            //方法体
        }
        public static int ad(int a , int b) {
    
    
            //方法体
        }
    }

(2) Method overloading example: Design a method to compare whether two integers are the same, such as an integer type
code example :

    public static void main(String[] args) {
    
    
        System.out.println(compare(6, 6));
    }

    public static boolean compare(int m, int n) {
    
    
        return m == n;
    }

Running results :
Insert image description here

5. Array

(1) Array traversal
Example: Create a method for array traversal, which requires the result of the traversal to be on one line. For example: [11, 22, 33, 44, 55]
Code example :

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1,4,5,3,6};
        pArr(arr);
    }

    public static void pArr(int[] a){
    
    
        System.out.print("[");
        for (int i = 0; i < a.length; i++) {
    
    
            if(i == a.length - 1){
    
    
                System.out.println(a[i] + "]");
            }else{
    
    
                System.out.print(a[i] + ", ");
            }
        }
    }

(2) Maximum value of an array
Example:
Code example for finding the maximum value of an element in an array :

public static void main(String[] args) {
    
    
        int[] a = {
    
    1,4,5,3,6};
        int maxnumber = getMax(a);
        System.out.println("maxnumber=" + maxnumber);
    }

    public static int getMax(int[] arr) {
    
    
        int max = arr[0];
        for(int a=1; a<arr.length; a++) {
    
    
            if(arr[a] > max) {
    
    
                max = arr[a];
            }
        }
        return max;
    }

Running results :
Insert image description here

6. Get the index

Example: Define a method to get a number at the index position in the array, and return the result to the calling place. If there are duplicates, just get the first one.
Code example :

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    2,4,3,9,5};
        int index = cons(arr, 9);
        System.out.println(index);
    }

    public static int cons(int[] a, int n) {
    
    
        //遍历arr得到每一个元素
        for (int i = 0; i < a.length; i++) {
    
    
            if(a[i] == n){
    
    
                return i;
            }
        }
        return -1;
    }

Running results :
Insert image description here

Guess you like

Origin blog.csdn.net/lolly114/article/details/130279004