[Java] 纯文本查看 复制代码 import java.util.Scanner;
public class DoTower {
public static void main(String[] args) {
int nDisks = 0;
System.out.print("请输入塔高:");
Scanner scan = new Scanner(System.in);
String read = scan.nextLine();
try {
nDisks = Integer.valueOf(read);
if (nDisks < 1) {
throw new RuntimeException();
}
} catch (Exception e) {
System.out.println("请输入大于等于1的整数!");
return;
}
int step = doTower(nDisks, 'A', 'B', 'C', 0);
System.out.println("此次共用"+step+"步");
}
public static int doTower(int topN, char from, char inter, char to, int step) {
++step;
if (topN == 1)
System.out.println("Disk 1: from " + from + " to " + to);
else {
step = doTower(topN - 1, from, to, inter, step);
System.out.println("Disk " + topN + ": from " + from + " to " + to);
step = doTower(topN - 1, inter, from, to, step);
}
return step;
}
} |