1, there are a pair of rabbits, from the 3rd month after birth every month, a pair of rabbits, the rabbit long to the third month after the birth of a pair of rabbits, if the rabbit is not dead, ask the 20th month of the rabbit logarithm is how much? (No Death rabbit)
(1) Array mode
package 递归.作业;public class TuziArray { public static void main(String[] args) { //定义数组 int arr[] = new int[100]; int m=20; arr[1] = 1;//前两个月兔子数量为1只 arr[2] = 1; arr[3] = 2; for(int i=1;i<=m;i++){ if(i>=3){ //规律为:斐波那契数列规律 arr[i] = arr[i-1] +arr[i-2]; } } System.out.println("第20个月的兔子对数为:"+arr[20]); }}
(2) Recursive method
package 递归.作业;public class Tuzi { public static void main(String[] args) { // 調用rabbit()方法 int rabbit = rabbit(20); System.out.println("第20个月的兔子对数为: " + rabbit); } public static int rabbit(int mouth) { // 前兩個月只有一對兔子 if (mouth == 1 || mouth == 2) { return 1; } // 上一个月的兔子数 int rabbit1 = rabbit(mouth - 1); // 上一个月的前一个月兔子数 int rabbit2 = rabbit(mouth - 2); // 斐波那契額函數 return rabbit1 + rabbit2; }}
2. Requirements: Recursive removal of contents with content
Suppose there is a demo folder under the project path with some folders and some files, please use recursive thinking to implement.
package 递归.作业;import java.io.File;public class FileDiGui2 { public static void main(String[] args) { // 封装File对象 File demo = new File("demo"); // 调用递归删除方法 deleteFile(demo); } // 方法递归:删除 public static void deleteFile(File demo) { // 获取该文件夹下的文件或文件夹路径名数组 File[] demoFile = demo.listFiles(); // 非空判断 if (demoFile != null) { // 遍历demofile数组对象 for (File file : demoFile) { // 判断file里面的对象是不是标准文件,如果是则递归调用该方法进行继续判断 if (file.isFile()) { deleteFile(file); } else {// 否则是一个文件夹,执行输出文件名,并删除 System.out.println(file.getName() + "---" + file.delete()); } } } } }
3. Requirements: Please put the absolute path of all Java end files in the E:\JavaSE directory to the output in the console.
package File类.作业;import java.io.File;public class OutputE { public static void main(String[] args) { // 创建文件对象 ,指向E:\\JavaSE File file = new File("E:\\JavaSE"); // 获取file对象内的文件/文件夹路径名数组 File[] files = file.listFiles(); // 遍历files数组 for (File f : files) { // 获取f对象文件名,判断是否以".java"结尾,如果是输出路径名 if (f.getName().endsWith(".java")) System.out.println(f); } } }
Method recursion and file example in Java