import java.io.*; public class MoveMain { public static void main (String[ ] args) { final int SENTINEL = -1; final String PROMPT = "\nPlease enter a non-negative integer or " + SENTINEL + " to quit: "; final String ERROR = "Error: the input must be a non-negative integer or " + SENTINEL; final String MESSAGE = " disk(s) can be moved from pole A to pole B " + "in the following step(s):\n\n"; BufferedReader reader = new BufferedReader (new InputStreamReader (System.in)); int n; while (true) { try { System.out.print (PROMPT); n = Integer.parseInt (reader.readLine()); if (n == SENTINEL) break; System.out.println (n + MESSAGE + move (n, 'A', 'B', 'C')); } // try catch (Exception e) { System.out.println (e); } // catch } // while } // method main /** * Determines the steps needed to move disks from an origin to a destination. * n * The worstTime(n) is O(2 ). * * @param n the number of disks to be moved. * @param orig the pole where the disks are originally. * @param dest the destination pole * @param temp the pole used for temporary storage. * * @return a String representation of the moves needed. * * @throws IllegalArgumentException if n is less than or equal to 0. */ public static String move (int n, char orig, char dest, char temp) { final String DIRECT_MOVE = "Move disk " + n + " from " + orig + " to " + dest + "\n"; if (n <= 0) throw new IllegalArgumentException( ); if (n == 1) return DIRECT_MOVE; String result = move (n - 1, orig, temp, dest); result += DIRECT_MOVE; result += move (n - 1, temp, dest, orig) ; return result; } // method move } // class MoveMain