Discuss / Java / 练习

练习

Topic source

何以忘言i

#1 Created at ... [Delete] [Delete and Lock User]

只需要在listDir方法外添加一个静态参数,负责记录层数即可

package com.itranswarp.learnjava;
import java.io.File;
import java.io.IOException;
/**
 * Learn Java from https://www.liaoxuefeng.com/
 * 
 * @author liaoxuefeng
 */
public class Main {
	public static void main(String[] args) throws IOException {
		File currentDir = new File("F:\\nextcloud备份\\我的思维导图");
		listDir(currentDir.getCanonicalFile());
	}
	
	static int depth=0;//添加一个静态参数
	
	static void listDir(File dir) {
		// TODO: 递归打印所有文件和子文件夹的内容
		File[] fs = dir.listFiles();
		if (fs != null) {
			for (File f : fs) {
				if (f.isFile()) {
					for(int i=0; i<depth; i++) {
						System.out.print(" ");
					}
					System.out.println(f.getName());
				}else if (f.isDirectory()) {
					for(int i=0; i<depth; i++) {
						System.out.print(" ");
					}
					System.out.println(f.getName() + "/");
					depth++;
					listDir(f);
				}
			}
		}
	}
}

何以忘言i

#2 Created at ... [Delete] [Delete and Lock User]

以上程序有bug


  • 1

Reply