// Hanoi2.java: // // illustrate what will go WRONG with recursion // if the PRECONDITION of a problem is violated. import java.io.*; class Hanoi2 { static void Hanoi(int ndisks, int frompeg, int topeg) { int thirdpeg; if (ndisks == 1) { /* ----- This is easy and I can do it ! ----- */ System.out.println("Move a disk from peg " + frompeg + " to " + topeg); } else { /* ------ This is tough, pass the buck... ------ */ thirdpeg = 6 - frompeg - topeg; // Find the free peg... System.out.println("Move a disk from peg " + frompeg + " to " + thirdpeg); Hanoi(ndisks-1, frompeg, topeg); // solve this for me... System.out.println("Move a disk from peg " + thirdpeg + " to " + topeg); } } public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); int n; System.out.print("How many disks: "); n = Integer.parseInt(stdin.readLine()); Hanoi(n, /* from */ 1, /* to */ 3); } }