Home  >  Article  >  Java  >  Introduction to the definition and use of Java methods

Introduction to the definition and use of Java methods

WBOY
WBOYforward
2023-05-07 19:55:05958browse

    1. Basic usage of methods

    1.1 What is a method

    A method is a code Fragment. Similar to "function" in C language. Method can be understood as a function, which can be used repeatedly.

    1.2 Method definition syntax

    Currently, when writing any method, it is written as:

    pubiic static return value return name (formal parameter list){

    Function body/method body

    }

    Code example: find the sum of 1-n

     /**
         * 求我们1-n的和
         * 函数名字必须采用小驼峰
         * @param n 输入一个数字
         */
        public static int sumAdd(int n){
            int sum = 0;
            for(int i = 1;i <= 10;i++){
                sum += i;
            }
            return sum;
        }
     
        public static void main(String[] args) {
            int ret = sumAdd(10);//方法的调用
        }

    Drawing explanation:

    Introduction to the definition and use of Java methods

    Chain calls of function return values:

    Let me give you an example based on the above example:

    /**
         * 求我们1-n的和
         * 函数名字必须采用小驼峰
         * @param n 输入一个数字
         */
        public static int sumAdd(int n){
            int sum = 0;
            for(int i = 1;i <= 10;i++){
                sum += i;
            }
            return sum;
        }
     
        public static void main(String[] args) {
            int ret = sumAdd(10);//方法的调用
            System.out.println(sumAdd(10)*2);//函数的返回值,支持链式调用
        }

    Drawing explanation:

    Introduction to the definition and use of Java methods

    There is no function declaration in Java. Regardless of whether your function is above or below the main function, you can call the

    1.3 method to open the memory.

    Function to open memory The space is called a function stack frame. When each function is called, a stack frame will be opened. The memory belonging to this function

    How the function is called in the memory space:

    Introduction to the definition and use of Java methods

    Example: Use the function method to find the sum of factorials of n

    用函数的方法求n的阶乘之和
    public static int Fac(int n) {
            int sum = 1;
            for (int i = 1; i <= n; i++) {
                sum = sum * i;
            }
            return sum;
        }
        /**
         * 求n的阶乘之和
         * @param
         */
        public static int facSum(int n){
            int ret = 0;
            for (int i = 1;i <= n; i++){
                ret = ret + Fac(i);
            }
            return ret;
        }
     
        public static void main(String[] args) {
     
            System.out.println(facSum(5));
        }
    }
    1.Java无法通过传地址的方式交换两个值的变量,后续会讲怎么做
    public class TestDemo {
        public static void swap(int a,int b){//交换两个变量的值
            int tmp = a;
            a = b;
            b = tmp;
        }
     
        public static void main(String[] args) {
            int a = 10;
            int b = 10;
            System.out.println("交换实参前:"+a+" " +b);
            swap(&a,b);//Java是做不到取地址的,如果想要写一个函数交换两个数的的值,只能把a和b的值放到堆上
            System.out.println("交换实参后:"+a+" " +b);
     
        }
    }

    2. Overloading of methods

    Sometimes we need to use a function that is compatible with multiple parameters at the same time, we will You can use method overloading

    Drawing explanation:

    Introduction to the definition and use of Java methods

    The names of the methods are all called add. But some add calculates int addition, and some adds double. Add; some calculate the addition of two numbers, and some calculate the addition of three numbers. The same method name provides different versions of implementation, which is called method overloading

    3. Use of methods

    Example question: Use functional method to write code to simulate three login scenarios

       public static void login(){
            int count = 3;
            Scanner scanner = new Scanner(System.in);
            while(count != 0){
                System.out.println("请输入你的密码");
                String password = scanner.nextLine();
                if(password.equals("123456")){//equals的返回值是true或者false
                    System.out.println("登录成功了");
                    break;
                }else{
                    count--;
                    System.out.println("你输错密码了,你还有"+count+"次机会");
     
                }
            }
     
        }
     
        public static void main(String[] args) {
            login();
     
        }

    Example question: Function to find the number of daffodils

     求水仙花数   
    public static void findNum(int n){
     
            for (int i = 1; i <=n; i++) {
                int count = 0;//数字的位数
                int tmp = i;
                while(tmp != 0){
                    count++;
                    tmp = tmp/10;
                }
                tmp = i;
                int sum = 0;
                while(tmp != 0){
                    sum += Math.pow(tmp%10,count);
                    tmp/=10;
                }
                if(sum == i){
                    System.out.println(i);
                }
     
            }
     
        }
     
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            findNum(n);
     
        }

    Example question: Find the odd number before the even number

    调整数组顺序使得奇数位于偶数之前,调整之后,不关心大小顺序
    public class TestDemo {
     
     
        public static void main(String[] args) {
            int[]arr = {1,2,3,4,5,6,7,8,9};
            int left = 0;
            int right = arr.length-1;
            while(left < right){
                while(left < right && arr[left] % 2 != 0){
                    left++;
                }
                while(left < right && arr[right] % 2== 0){
                    right--;
                }
                int tmp = arr[left];
                arr[left] = arr[right];
                arr[right] = tmp;
            }
            for (int i = 0; i <arr.length ; i++) {
                System.out.print(arr[i]+" ");
     
            }
     
        }
    
    }

    Example question: Function to find the maximum value of three numbers

    1.用函数求三个数的最大值
    public class TestDemo {
     
     
     
        public static int Max(int a,int b){
            return a > b? a : b;
     
        }
            public static int Max1(int a,int b,int c){
            return Max(Max(a,b),c);
            }
     
        public static void main(String[] args) {
            System.out.println(Max1(4, 6, 8));
     
        }
     
    }

    The above is the detailed content of Introduction to the definition and use of Java methods. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete