关于递归调用中是否一定需要返回值和参数问题。

关于递归调用中是否一定需要返回值和参数问题。我答案是不一定,两者都可以没有,只需要满足出递归的条件即可。

我们先来看看递归调用中需要注意的事项:

1.递归一定要有出口,否则就是死递归。

2.递归的次数不能太多,否则会出现内存溢出。

3.构造方法不能递归使用

回归正题:

第一种情况没有返回值的情况,因为不是特意测试递归的demo。只是在多级文件的复制中用到了,所以代码有点多

/**
 *@author 波波
 *@date 2020年7月20日
 *2、复制多级文件夹 
	举例:E:\JavaSE\day25\code\demos
		复制到:F:\
 */
public class Demo2 {
	public static void main(String[] args) throws IOException {
//		封装
		File src = new File("E:\\JavaSE\\day25\\code\\demos");
		File des = new File("F:\\");
		copy(src,des);
	}

	private static void copy(File src, File des) throws IOException {
//	或者先进来就判断是否是文件夹,没有创建,在遍历	
		//		获取src文件
		File[] listFiles = src.listFiles();
		for (File file : listFiles) {
//		遍历src如果是文件就直接复制粘贴,如果不是就递归调用
			if(file.isDirectory()) {
//				获取名字
				String srcName = src.getName();
//				封装一下
				File newFile = new File(des, srcName);
//				如果newFile不存在就创建一个
				if (!newFile.exists()) {
					newFile.mkdir();
				}
//              递归调用
				copy(file, newFile);
			}else {
//				调用文件的复制
				copy2(src,new File(des,src.getName()));
			}
		}
	
	
	}

	private static void copy2(File src, File desfile) throws IOException {
//		封装
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desfile));
//		读写
		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys,0,len);
		}
		bis.close();
		bos.close();
	}
}

第二中情况,没有参数的递归。 

/**
 *@author 波波
 *@date 2020年7月23日
 *没有参数的递归测试
 */
public class DiguiTest {
	public static void main(String[] args) {
		Test t = new Test();
		t.digui();
	}
}
class Test{
	 int i = 0;
	public  void digui() {
		if(i < 2) {
			i++;
			digui();
			
		} 
		System.out.println("test"+i+"次");
	}
}

 正在学习编程的小菜一枚,有错误和建议欢迎大家来提。

猜你喜欢

转载自blog.csdn.net/weixin_45215610/article/details/107567751