自定义函数
Ps:素材来源:MOOC《Java核心技术》。目的是记录自己的学习历程,与商业利益无关。所有步骤都是自己根据课程内容编写,所以投原创啦!
★哔哩哔哩~搜索:这里是火同学 观看视频介绍 大家多多点赞三连哦★
一,自定义函数(1)
- 示例
注意:a,b为实参。m,n为形参
public class FactorialTest {
public static void main(String[] args)
{
int a,b,c;
a=1;
b=2;
c=FactorialTest.add(a,b);
System.out.println("c is "+ c);
}
public static int add(int m,int n)
{
return m+n;
}
}
二,自定义函数(2)
- 递归函数
public class FunctionTest {
public static void main(String[] args)
{
int a =5;
int b = FactorialCalculation(a);
System.out.println("The factorpal of "+ a + " is "+b);
}
public static int FactorialCalculation(int m){
if(m>1)
{
return m*FactorialCalculation(m-1);
}
else
{
return 1;
}
}
}
运行结果:
三,自定义函数(3)
1)了解重载含义
- 函数可以相互调用
- 函数重载条件:函数名,形参类型,个数
2)代码表示
public class OverloadTest {
public static void main(String[] args){
int a = 1,b = 2;
System.out.println(add(1,2));
System.out.println(add(3.5,4.5));
}
public static int add(int a,int b)
{
return a + b;
}
public static double add(double m,double n)
{
return m + n;
}
/*
* 以下函数非法,和第九行的函数名相同
* public static double add(int m,int n)
* {
* return m+n;
* }
*/
}