方法&递归&重载

方法&递归&重载


最近在看以前的一些笔记,打算都整理下,减轻下电脑磁盘大哥的负担。如果对小伙伴有作用,麻烦点个赞 比个❤

方法

//语法:
//访问权限修饰符  其他修饰符  返回值类型  方法名称(参数列表) {
//	//方法体【函数体】
//	return 返回值;
//}
4.拥有返回值的方法
public static int sum4(int a,int b){
	return a+b;
}
1. 最简单的无参方法
void sum1(){
	System.out.println("加法操作");
}
2. 拥有修饰符的无参方法
public static void sum2(){
	System.out.println("加法操作");
}
3. 拥有参数的方法
public static void sum3(int a,int b){
	System.out.println(a+b);
}
public static int sum4(int a,int b){
	return a+b;
}
public static int sum5(){
	int x=20;
	int y=28;
	int z=x+y;
	return z;
}

方法调用

//方法调用练习
class TextDemo{
	public static void main(String[] args){
		System.out.println("start");
		//需求:打印多遍九九乘法表
		print();
		print();
		print();
		//...
		System.out.println("end");
	}
	public static void print(){
		for(int i=1;i<=9;i++){
			for(int j=1;j<=i;j++){
				System.oput.print(j+"x"+i+"="+i*j+"\t");
			}
			System.out.println();
		}
	}
}

方法重载

同一个类中,方法名字相同,参数列表不同。则是重载
注意:
1. 参数列表的不同包括,参数个数不同,参数数据类型不同,参数顺序不同
2. 方法的重载与方法的修饰符和返回值没有任何关系

//同一个类中,方法名字相同,参数列表不同。则是重载
class TextDemo{
	public static void main(String[] args){
		show();
		show(10);
		show("10");
		show("10",10);
	}	
	public static void show(){
		System.put.println("无参无返回值的show");
	}
	public static void show(int a){
		System.out.println("int的show");
	}
	public static void show(String a){
		System.out.println("String的show");
	}
	public static void show(String a, int b){
		System.out.println("String int的show");
	}
}

递归

在一个方法的方法体内调用该方法本身,称为方法的递归
方法递归包含了一种隐式的循环,会重复执行某段代码,但是这种重复不需要使用循环语句来进行控制
出现问题: StackOverFlowError 栈空间溢出异常,所以递归不能一直运行,一定要有结束条件。

//求斐波那契数列中的某个数
class DiGuiDemo{
	public static void main(String[] args){
		int result=fun(10);
		Ststem.out.println(result);
	}
	public static int fun(int n){
		if(n==1||n==2){
			return 1;
	    }else{
			return fun(n-1)+fun(n-2);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/l1996729/article/details/106567761