public class SimpleHanoi
1: import java.util.Scanner;
3: /**
4: * Print the steps required to solve the towers of Hanoi problem for any size.
5: *
6: * @author Mark Young (A00000000)
7: */
8: public class SimpleHanoi {
10: /** The total number of moves made so far */
11: private static int numMoves = 0;
13: public static void main(String[] args) {
14: // introduce yourself
15: System.out.print("\n\n"
16: + "Simple Hanoi\n"
17: + "----------\n\n"
18: + "This application tells you how to solve "
19: + "the Towers of Hanoi problem.\n\n");
21: // get the number of disks from the user
22: Scanner kbd = new Scanner(System.in);
23: System.out.print("How many disks? ");
24: int numDisks = kbd.nextInt();
25: kbd.nextLine();
27: // show all the moves required
28: showMoves(numDisks, "A", "C", "B");
30: // report the total number of moves made
31: System.out.print("\n"
32: + "Total moves: " + numMoves + "\n\n");
33: }
35: /**
36: * Show all the moves required to solve the towers of Hanoi problem.
37: *
38: * @param n the number of disks needing to be moved
39: * @param s the name of the starting peg
40: * @param f the name of the ending peg
41: * @param x the name of the extra peg
42: */
43: private static void showMoves(int n, String s, String f, String x) {
44: // if there are any disks to move
45: if (n > 0) {
46: // show how to move the smaller disks out of the way
47: showMoves(n-1, s, x, f);
49: // show moving the base disk to its final position
50: System.out.printf("Move top disk from %s to %s.\n", s, f);
52: // count that move
53: numMoves++;
55: // show how to move the smaller disks back on top of the base
56: showMoves(n-1, x, f, s);
57: }
58: }
59: }