/* TowersOfHanoi.java       Authors: Koffman & Wolz * Class that solves the towers of Hanoi problem. * Uses KeyIn and JOptionPane. */import psJava.KeyIn;import javax.swing.JOptionPane;public class TowersOfHanoi {  // Data fields  private int numDisks;  private char sourcePeg;  private char destinationPeg;  private char sparePeg;  // Methods  // precondition : fromPeg, toPeg, auxPeg, and  //   n are defined.  // postcondition: Displays a list of instructions to  //   move n disks from fromPeg to toPeg  //   using auxPeg as an intermediary.  private void tower(char fromPeg, char toPeg,                    char auxPeg, int n) {    if (n == 1)       System.out.println("Move disk 1 from peg " +                          fromPeg + " to peg " + toPeg);    else { // recursive step       tower (fromPeg, auxPeg, toPeg, n-1);       System.out.println("Move disk " + n +              " from peg " + fromPeg + " to peg " + toPeg);       tower(auxPeg, toPeg, fromPeg, n-1);    }  }  // precondition: arguments are defined.  // postcondition: recursive method is started.  public void tower() {    tower(sourcePeg, destinationPeg, sparePeg, numDisks);  }  // postcondition: Reads the number of disks and sourcePeg  //   and destinationPeg. Sets sparePeg to the unused peg.  public void readTowerData() {     numDisks = KeyIn.readInt("How many disks", 1, 8);     // Get source and destination pegs.     sourcePeg = KeyIn.readChar("Enter the source peg (A,B,C)");     destinationPeg =          KeyIn.readChar("Enter the destination peg (A,B,C)");     while (sourcePeg == destinationPeg) {        JOptionPane.showMessageDialog(null,              "source and destination can't be the same!",              "Error", JOptionPane.ERROR_MESSAGE);        destinationPeg =              KeyIn.readChar("Enter destination (A,B,C)");     }     // Set sparePeg to the unused peg.     String pegsUsed = "" + sourcePeg + destinationPeg;     // Find peg that is not used.     for (char nextCh = 'A'; nextCh <= 'C'; nextCh++) {        if (pegsUsed.indexOf(nextCh) < 0) {          sparePeg = nextCh;          return;        }     }  }} // class TowersOfHanoi