当前位置 博文首页 > zhouqiyuan1233的博客:Java方法详解

    zhouqiyuan1233的博客:Java方法详解

    作者:[db:作者] 时间:2021-08-09 22:20

    教程链接


    1. 何谓方法

    在这里插入图片描述

    public class Demo01 {
        //main方法
        public static void main(String[] args) {
            System.out.println(add(1, 2));
        }
    
        //加入static修饰符,方法才能在自己的main方法中调用
        public static int add(int a, int b) {
            return a + b;
        }
    }
    
    

    2. 方法的定义

    在这里插入图片描述

    public class Demo01 {
        public static void main(String[] args) {
            //这里的 1 2 是实际参数
            System.out.println(add(1, 2));
        }
    
        //这里的 a b 是形式参数
        public static int add(int a, int b) {
            return a + b;
        }
    }
    

    关于JAVA的protected类型

    returen除了可以返回值,还能终止方法,遇见return并执行后,方法终止


    3. 方法调用

    在这里插入图片描述


    4.方法重载

    在同一个类中,方法名相同,但是参数不同。

    
    	System.out.println(add(1, 2));
    	
    	public static int add(int a, int b) {
            return a + b;
        }
        
        System.out.println(add(1.0, 2.0));
        public static double add(double a, double b) {
            return a + b;
        }
    

    传入参数会自动匹配相应的方法。如果没有知道匹配的方法就会报错。
    参数数量也可以改变
    在这里插入图片描述


    5.可变参数

    在这里插入图片描述

    public class Demo03 {
        public static void main(String[] args) {
            Demo03 demo03 = new Demo03();
            demo03.test(1,2,3,4,5);
    
        }
    
        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]);
            System.out.println(i[4]);
        }
    }
    

    本质上就是数组

    在这里插入图片描述
    再次强调:只能放在最后,并且所有变量类型要相同。

    实例:比较一组数中最大的数,并输出。

    public class Demo04 {
        public static void main(String[] args) {
            //调用可变参数方法
            printMax(1.0, 1111, 15111);
            //也能传递数组
            printMax(new double[]{1,2,3,4,5,6});
        }
    
        public static void printMax(double... num) {
            if (num.length == 0) {
                System.out.println("内容不能为空!");
                return;
            }
    
            double result = num[0];
            //排序
            for (int i = 0; i < num.length; i++) {
                if (num[i] > result) {
                    result = num[i];
                }
    
            }
            System.out.println("最大值为:" + result);
        }
    }
    

    6.递归

    在这里插入图片描述
    在这里插入图片描述

    实例:计算阶乘

    public class Demo05 {
        public static void main(String[] args) {
            System.out.println(f(5));
        }
    
        //实现计算阶乘
        public static int f(int n) {
            //当 n=1 时,跳出递归
            if (n == 1) {
                return 1;
            } else {
                return n * f(n - 1);
            }
        }
    }
    

    注意:递归会占用大量电脑内存,如果计算数量过大,会导致内存溢出(刚才试了下递归100.结果是0。 23333),能不用递归就不要用



    这篇博客断断续续写了一个月,刚开学事情有点多。。。

    cs