方法的重载、方法的递归

1.方法的重载

含义:方法与方法之间的关系

条件:

1.在同一个类中

2.方法名一致

3.参数列表的个数或类型不一致

4.与返回值无关(方法是否有返回值、返回什么值跟方法的重载关系是无关的)

好处:系统会根据实参类型自动匹配到对应的方法里

        需求1:设计一个方法,传入两个int值,返回最大值
        需求2:设计一个方法,传入三个int值,返回最大值
        需求3:设计一个方法,传入两个double值,返回最大值
        需求4:设计一个方法,传入三个double值,返回最大值

public static void main(String[] args){
		
		//打印getMax的方法,这个方法必须有返回值才能打印,否则会报错
		System.out.println(getMax(10.1,20));
	}

	
	public static int getMax(int a,int b){
		int max = (a>b)?a:b;
		return max;
	}
	
	public static int getMax(int a,int b,int c){
		int max = getMax(a,b);
		max = getMax(a,b);//改进后调用方法的代码
		return max;
	}
	
	public static double getMax(double a,double b){
		double max = (a>b)?a:b;
		return max;
	}
	
	public static double getMax(double a,double b,double c){
		double max = getMax(a,b);
		max = getMax(a,b);
		return max;
	}
}

2.方法的递归

1.含义:方法调用方法自身

2.经验:找规律、找出口

1).找规律:知道方法何时调用方法自身 ​ 2).找出口:知道方法何时结束

需求:设计一个方法,传入int类的值n,求n的阶乘
        分析:
            5! -> 1*2*3*4*5 -> 4!*5
            4! -> 1*2*3*4    -> 3!*4
            3! -> 1*2*3        -> 2!*3
            2! -> 1*2        -> 1!*2
            1! -> 1            -> 1
        
            找规律:n! = (n-1)! * n;
            找出口:1! = 1;

public static void main(String[] args){		
		int num = getFactorial(5);
		System.out.println(num);
	}	
	public static int getFactorial(int n){		
		if(n != 1){
			return getFactorial(n-1) * n;
		}else{
			return 1;
		}
	}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值