System.out.println(result);
}
public int factorial(int index){
if(index==1){
return 1;
}else{
return factorial(index-1)*index;
}
}
}
程序执行流程如下:
③列出某个目录下所有的子目录和文件
求解代码:
[html] view plaincopyprint?
/*
* time:2012.12.2
* author:王金宇
* description:列出某个目录下所有的子目录和文件
*/
public class ListDir {
static void getDir(String strPath) throws Exception {
try {
File f = new File(strPath);
if (f.isDirectory()) {
File[] fList = f.listFiles();
for (int j = 0; j < fList.length; j++) {
if (fList[j].isDirectory()) {
System.out.println(fList[j].getPath());
getDir(fList[j].getPath()); // 在getDir函数里面又调用了getDir函数本身
}
}
for (int j = 0; j < fList.length; j++) {
if (fList[j].isFile()) {
System.out.println(fList[j].getPath());
}
}
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
public static void main(String[] args) {
String strPath = "E:";
System.out.println(strPath);
try {
getDir(strPath);
} catch (Exception e) {
}
}
}
/*
* time:2012.12.2
* author:王金宇
* description:列出某个目录下所有的子目录和文件
*/
public class ListDir {
static void getDir(String strPath) throws Exception {
try {
File f = new File(strPath);
if (f.isDirectory()) {
File[] fList = f.listFiles();
for (int j = 0; j < fList.length; j++) {
if (fList[j].isDirectory()) {
System.out.println(fList[j].getPath());
getDir(fList[j].getPath()); // 在getDir函数里面又调用了getDir函数本身
}
}
for (int j = 0; j < fList.length; j++) {
if (fList[j].isFile()) {
System.out.println(fList[j].getPath());
}
}
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
public static void main(String[] args) {
String strPath = "E:";
System.out.println(strPath);
try {
getDir(strPath);
} catch (Exception e) {
}
}
}
这个流程图你懂得,看文件数目了,大家自己分析吧。
④汉诺塔问题
这是递归的超经典的例子,几乎每本程序设计书上谈到递归都会介绍。具体情景不再赘述。以我上述的方法观之:
(1)递归的出口在于盘子数为1的时候 。
(2)向出口逼近:如果不是1,是n ,则我们先挪动上面n-1块盘子,等上面挪完,即递归返回的时候,我们挪动最底下的盘子。
求解代码:
[html] view plaincopyprint?
import javax.swing.JOptionPane;
/*
* time:2012.12.2
* author:王金宇
* description:
*/
public class Hanoi {
private final static String from = "盘子B";
private final static String to = "盘子C";
private final static String mid = "盘子A";
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("请输入你要移动的盘子数");
int num = Integer.parseInt(input);
Hanoi.move(num, from, mid, to);
}
private static void move(int num, String from2, String mid2, String to2) {
if (num == 1) {
System.out.println("移动盘子1 从" + from2 + "到" + to2);
} else {
move(num - 1, from2, to2, mid2);
System.out.println("移动盘子" + num + " 从" + from2 + "到" + to2);
move(num - 1, mid2, from2, to2);
}
}
}
import javax.swing.JOptionPane;
/*
* time:2012.12.2
* author:王金宇
* description:
*/
public class Hanoi {
private final static String from = "盘子B";