Java方法

一、方法的定义及调用

在这里插入图片描述

package com.roc.method;

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

    public static int add(int a, int b) {  //形参
        return a + b;
    }
}

package com.roc.method;

public class Demo02 {
    public static void main(String[] args) {
        int big = compare(10, 10);
        System.out.println(big);
    }

    public static int compare(int a, int b) {
        if (a == b) {
            System.out.println(a + "=" + b);
            return 0;
        }
        return a > b ? a : b;
    }
}

二、方法重载

在这里插入图片描述

package com.roc.method;

public class Demo03 {
    public static void main(String[] args) {
        double big = compare(10.0, 10.0);
        System.out.println(big);
    }

    public static int compare(int a, int b) {
        if (a == b) {
            System.out.println(a + "=" + b);
            return 0;
        }
        return a > b ? a : b;
    }

    public static double compare(double a, double b) {
        if (a == b) {
            System.out.println(a + "=" + b);
            return 0;
        }
        return a > b ? a : b;
    }
}

三、命令行传参

有时候希望运行一个程序时,在传递给她次消息在,这就靠命令行参数给main()函数实现。
在这里插入图片描述

四、可变参数

在这里插入图片描述

package com.roc.method;
//可变参数  不定项参数
public class Demo04 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();
        demo04.test(1, 2, 3, 4, 5);

        printMax(1.0, 2, 3.2, 0.9);
        printMax(new double[]{10, 20.0, 5.1, 2});
    }

    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 static void printMax(double... numbers) {
        if (numbers.length == 0) {
            System.out.println("No argument passed");
            return;
        }
        double result = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > result) {
                result = numbers[i];
            }
        }
        System.out.println("最大的数为:" + result);
    }
}

五、递归

方法自己调用自己
递归头: 什么时候不调用自己的方法
递归体: 递归函数
递归采用的是栈机制,逐步递归就是压栈,当深度很高的时候,时空性就非常不好,能不要递归就不递归。

在这里插入图片描述

package com.roc.method;

// n的阶乘
public class Demo05 {
    public static void main(String[] args) {
        System.out.println("阶乘:" + f(5));
    }

    public static int f(int n) {
        if (n == 1) {
            return 1;
        } else {
            return n * f(n - 1);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值