JAVA basic exercises-recursion, get all files in the folder, delete a file, file copy, hierarchical printing, Fibonacci sequence, Joseph ring

Recursion

1. Concept: Invoke yourself
Case: Requirements: Count 5!
Method 1: Use for loop

int result=1;
		for (int i = 1; i <=5; i++) {
    
    
			result=result*i;
		}
		System.out.println(result);
	}

Method two: use recursion

public static int fun(int num) {
    
    
		if (num ==1) {
    
    
			return 1;
		}else {
    
    
			return num*fun(num-1);
		}
	}

Disadvantages: Recursion cannot be called too many times, otherwise the stack memory will overflow.
benefit: No need to know the number of cycles
problem: The
constructor cannot use recursive calls. A recursive call can have a return value or no return value.

Recursive exercises (1)

Requirements: Input a folder path from the keyboard, and print out all the .java file names in the folder.
Analysis:
1. Get all the files and folders under the folder path and store them in the File array
2. Traverse the array and judge each file or folder.
3. If it is a file and the suffix is ​​.java, print it
4. If it is a folder, call it recursively

public class Demo1_Test {
    
    

	public static void main(String[] args) {
    
    
		File dir =getDir();
		printJavaFile(dir);
	}
	public static File getDir() {
    
    
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个文件夹路径:");
		while (true) {
    
    
			String line =scanner.nextLine();
			File dir =new File(line);
			if (!dir.exists()) {
    
    
				System.out.println("您录入的文件夹路径不存在,请重新录入");
			}else if (dir.isFile()) {
    
    
				System.out.println("您录入的是文件夹路径,请重新录入文件路径");
			}else {
    
    
				return dir;
			}
		}
	}
	
	//获取文件夹路径下的所有.java文件
	//返回值类型void
	//参数列表File dir
	public static void printJavaFile(File dir) {
    
    
		//获取到该文件路径下的所有的文件和文件夹,存储在File数组中
		File[] subFiles =dir.listFiles();
		//遍历数组,对每一个文件或文件夹做判断
		for (File subFile :subFiles) {
    
    
			//如果是文件,并且后缀名是.java的就打印
			if (subFile.isFile()&&subFile.getName().endsWith(".java")) {
    
    
				System.out.println(subFile);
			//如果是文件夹,就递归调用
			}else if (subFile.isDirectory()) {
    
    
				printJavaFile(subFile);
			}
				
			
		}
	}
}

The effect is as follows:
Insert picture description here

Recursive exercises (2)

Requirement: Receive a folder path from the keyboard, and count the size of the folder
Analysis:
Receive a folder path from the keyboard

  1. Create keyboard entry objects
  2. Define a wireless loop
  3. Store and encapsulate the results of keyboard entry into File objects
  4. Judge the File object
  5. Return folder path object

Count the size of the folder

  1. Define a sum variable
  2. Get all files and folders in the folder ListFiles();
  3. Traverse the array
  4. If it is a file, calculate the size and add it up
  5. Judge it is a folder, call recursively
public class Demo2_Test {
    
    

	public static void main(String[] args) {
    
    
		//File dir =new File("d:\\day15");
		//System.out.println(dir.length());//直接获取文件夹的结果是0
		File dir =getFile();
		System.out.println(getFileLength(dir));
	}
	
	public static File getFile() {
    
    
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个文件夹路径");
		while (true) {
    
    
			String line =scanner.nextLine();
			File dir = new File(line);
			//对File对象进行判断
			if (!dir.exists()) {
    
    
				System.out.println("文件路径不存在!");
			}else if(dir.isFile()) {
    
    
				System.out.println("这是文件夹路径,请输入文件路径");
			}
			else {
    
    
				//将文件夹路径对象返回
				return dir;
			}
		}	
	}
	//统计文件大小。返回值类型long,参数列表File dir
	public static long getFileLength(File dir) {
    
    
		//定义一个求和变量
		long len =0;
		//获取该文件夹下所有的文件和文件夹ListFiles
		File [] subFiles =dir.listFiles();
		//遍历数组
		for (File subFile : subFiles) {
    
    
			//判断如果是文件就计算大小并累加
			if (subFile.isFile()) {
    
    
				len +=subFile.length();
			}else {
    
    
				//如果是文件夹的话就在继续递归调用
				len+=getFileLength(subFile);
			}
			
		}
		return len;
	}
	
}

The effect is as follows:
Insert picture description here

Recursive exercises (3)

Requirements: Enter the path from the console and delete the folder

public class Demo3_Test {
    
    

	public static void main(String[] args) {
    
    
		File file =getFile();
		deleteFile(file);
	}
	
	//删除文件夹
	public static void deleteFile(File dir) {
    
    
		File[]subFiles=dir.listFiles();
		//遍历数组
		for (File subFile : subFiles) {
    
    
			if (subFile.isFile()) {
    
    
				//如果是文件夹就直接删除
				subFile.delete();
			}else {
    
    
				deleteFile(subFile);
			}
			
		}
		//循环结束后,把空文件夹删掉
		dir.delete();
	}
	
	public static File getFile() {
    
    
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个文件路径名称");
		while (true) {
    
    
			String line =scanner.nextLine();
			File dir =new File(line);
			if (!dir.exists()) {
    
    
				System.out.println("文件路径不存在或输入有误");
			}else if(dir.isFile()){
    
    
				System.out.println("这是文件夹路径,请输入文件路径");
			}else {
    
    
				return dir;
			}
		}
	}
}

Recursive exercises (4)

Requirement: Receive two folder paths from the keyboard, and copy one of the folders (containing content) to another folder.
Analysis:

  1. Create the original folder in the target folder
  2. Get all files and folders in the original folder and store them in the File array
  3. Traverse the array
  4. If it is a file, use io stream to read and write
  5. If it is a folder, call it recursively
public class Demo4_Test {
    
    

	public static void main(String[] args) throws IOException {
    
    
		File src =getFile();
		File desc =getFile();
		if (src.equals(desc)) {
    
    
			System.out.println("目标文件夹是原文件夹的子文件夹");
		}else {
    
    
			copy(src,desc);
		}
		
 
	}
	//把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
	//返回值类型void
	//参数列表File src,File desc
	public  static void copy(File src, File desc) throws IOException {
    
    
	//在目标文件夹中创建原文件夹
		File newDir =new File(desc,src.getName());
		newDir.mkdir();
		//获取原文件夹中所有的文件和文件夹,存储在File数组中
		File[] subFiles =src.listFiles();
		for (File subFile : subFiles) {
    
    
			//如果是文件用io读写
			if (subFile.isFile()) {
    
    
				BufferedInputStream bis =new BufferedInputStream(new FileInputStream(subFile));
				BufferedOutputStream bos =
						new BufferedOutputStream(new FileOutputStream(new File(newDir,subFile.getName())));
				int b;
				while ((b=bis.read())!=-1) {
    
    
					bos.write(b);
				}
				bis.close();
				bos.close();
			}else {
    
    
				copy(subFile, newDir);
			}
			
		}
	}
	public static File getFile() {
    
    
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个文件路径");
		while (true) {
    
    
			String line =scanner.nextLine();
			File dir =new File(line);
			if (!dir.exists()) {
    
    
				System.out.println("文件路径不存在");
			}
			else if (dir.isFile()) {
    
    
				System.out.println("这是文件夹路径,请输入文件路径");
			}else {
    
    
				return dir;
			}
		}
	}
}

Recursive exercises (5)

Requirement: Print by level, receive a folder path from the keyboard, and print all files and folder names in the folder by level, for example:
aaa is a folder with bbb.txt, ccc.txt, ddd.txt in it These files, there are folders like eee, fff.txt and ggg.txt in eee, print out the hierarchy

Analysis:
1. Get all files and folders, and the returned File array
2. Traverse the array
3. Whether it is a file or a folder, it needs to be printed directly
4. If it is a folder, call recursively

public class Demo5_Test {
    
    

	public static void main(String[] args) {
    
    
		File dir =getFile();
		printLev(dir,0);

	} 
	public static void printLev(File dir ,int level) {
    
    
		//把文件夹中的文件和文件夹放入File数组中
		File[] subFiles =dir.listFiles();
		for (File subFile : subFiles) {
    
    
			for (int i = 0; i <=level; i++) {
    
    
				System.out.print("\t");
			}
			//不论是文件还是文件夹,都需要直接打印
			System.out.println(subFile);
			//如果是文件夹,递归调用
			if (subFile.isDirectory()) {
    
    
				printLev(subFile,level+1);
				//改变level++或者++level结果均不同
			}
		}
		
	}
	public static File getFile(){
    
    
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个文件路径");
		while (true) {
    
    
			String line =scanner.nextLine();
			File dir =new File(line);
			if (!dir.exists()) {
    
    
				System.out.println("输入的文件路径不存在");
			}else if (dir.isFile()) {
    
    
				System.out.println("请输入一个文件路径");
			}else {
    
    
				return dir;
			}
		}
	}
}

When considering this type of problem, you must consider the stacking problem

Recursive exercises (6)

Requirement: Fibonacci sequence
The meaning of the sequence is that the sum of the previous two items is equal to the current item. an =an+1+an-2

public static int fun(int num) {
    
    
		if (num ==1 || num==2) {
    
    
			return 1;
		}else {
    
    
			return fun(num-2)+fun(num-1);
		}
	}
}

Joseph Ring

Demand: looking for lucky numbers

public class Demo8_Test {
    
    
public static void main(String[] args) {
    
    
	System.out.println(getLucklyNum(8));
}
public static int getLucklyNum(int num) {
    
    
	ArrayList<Integer> list =new ArrayList<Integer>();		//创建集合存储1到num的对象
	for (int i = 0; i < num; i++) {
    
    
		list.add(i);
	}
	int count =1;		//用于数数,只要是3的倍数就循环
	for (int i = 0;list.size()!=1; i++) {
    
    	//只要集合中人数超过1,就不断地删除
		if (i == list.size()) {
    
    
			i=0;							//重新归零
		}
		if (count%3==0) {
    
    					//如果是3的倍数就删除
			list.remove(i--);
		}
		count++;
	}
	return list.get(0);
}

}

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/109034841