1 斐波那契数列
/**
* 递归是一个很费资源的操作,当n=50是,一般计算机运行很慢
* @author zhangli
*
*/
public class Fibonacci
{
public static void main(String[] args)
{
System.out.println(f(10));
}
/**
* 1 1 2 3 5 8 13 ***
*
* @param n
* @return
*/
public static int f(int n)
{
//前两个元素均直接返回1
if(n == 1 || n == 2)
{
return 1;
}
else
{
//其他元素=前两个元素之和
return f(n - 1) + f(n - 2);
}
}
}
2 打印某个目录下所有的文件及其文件夹
import java.io.File;
/**
* 模拟windows中命令行下tree的实现,使用递归
* @author zhangli
*
*/
public class MyTree
{
public static void main(String[] args)
{
File f = new File("C:\\Users\\zhangli");
showFile(f, 0);
}
/**
* 把str输出count遍
*
* @param count
* @param str
* 如果str="123",count=2; 那结果就是 "123123"
* @return
*/
public static String printString(int count, String str)
{
// 先声明缓冲的大小
StringBuffer sb = new StringBuffer(64);
for (int i = 0; i < count; i++)
{
sb.append(str);
}
return sb.toString();
}
/**
* 遍历文件件下所有文件节点
*
* @param f
* 当前浏览的文件夹
* @param level
* 当前文件夹的层数
*/
public static void showFile(File f, int level)
{
//实例化该文件夹下所有的文件为File
File childs[] = f.listFiles();
if(childs != null)
{
for (int i = 0; i < childs.length; i++)
{
//不管是不是文件,总要输出
System.out.println(printString(level, "\t")
+ childs[i].getName());
//如果是文件夹,陷入继续调用本方法
if(childs[i].isDirectory())
{
showFile(childs[i], level + 1);
}
}
}
else
{
System.out.println(printString(level, "\t") + f.getName());
}
}
}