Source of SimpleHanoi.java


  1: import java.util.Scanner;
  2: 
  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 {
  9: 
 10:     /** The total number of moves made so far */
 11:     private static int numMoves = 0;
 12: 
 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");
 20: 
 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();
 26: 
 27:         // show all the moves required
 28:         showMoves(numDisks, "A", "C", "B");
 29: 
 30:         // report the total number of moves made
 31:         System.out.print("\n"
 32:                 + "Total moves: " + numMoves + "\n\n");
 33:     }
 34: 
 35:     /**
 36:      * Show all the moves required to solve the towers of Hanoi problem.
 37:      *
 38:      * @param numDisks     the number of disks needing to be moved
 39:      * @param start     the name of the starting peg
 40:      * @param finish     the name of the ending peg
 41:      * @param extra     the name of the extra peg
 42:      */
 43:     private static void showMoves(int numDisks, 
 44:             String start, String finish, String extra) {
 45:         // if there are any disks to move
 46:         if (numDisks > 0) {
 47:             // show how to move the smaller disks out of the way
 48:             showMoves(numDisks - 1, start, extra, finish);
 49: 
 50:             // show moving the base disk to its final position
 51:             System.out.printf("Move top disk from %s to %s.\n", start, finish);
 52: 
 53:             // count that move
 54:             numMoves++;
 55: 
 56:             // show how to move the smaller disks back on top of the base
 57:             showMoves(numDisks - 1, extra, finish, start);
 58:         }
 59:     }
 60: }