// Towers of Hanoi, classic problem (recursive method)
// Java How to program, 5/e, Exercise 6.37-38
Import javax.swing. * ;
Import java.awt. * ;
Import java.awt.event. * ;
Public class hanoitowers extends JApplet Implements ActionListener {
intNumber , starting, destination, temp;
JLabel Numberlabel, Startinglabel, Destinationlabel, Templabel;
JTextField Numberfield, Startingfield, Destinationfield, Tempfield;
JTextArea output;
JScrollPane scroller;
Public voidInit ()
{
Container Container=Getcontentpane ();
Container.setlayout (NewFlowLayout ());
Numberlabel= NewJLabel ("Enter the number of disks:");
Container.add (Numberlabel);
Numberfield=NewJTextField (Ten);
Container.add (Numberfield);
Startinglabel= NewJLabel ("Enter The starting tower:");
Container.add (Startinglabel);
Startingfield=NewJTextField (Ten);
Container.add (Startingfield);
Destinationlabel= NewJLabel ("Enter The destination tower:");
Container.add (Destinationlabel);
Destinationfield=NewJTextField (Ten);
Container.add (Destinationfield);
Templabel= NewJLabel ("Enter The temporary tower:");
Container.add (Templabel);
Tempfield=NewJTextField (Ten);
Container.add (Tempfield);
Tempfield.addactionlistener ( This);
Output=NewJTextArea ( -, -);
Scroller=NewJScrollPane (output);
Container.add (scroller);
}
Public voidActionperformed (ActionEvent event)
{
number=integer.parseint (Numberfield.gettext ());
Starting=integer.parseint (Startingfield.gettext ());
Destination=integer.parseint (Destinationfield.gettext ());
Temp=integer.parseint (Tempfield.gettext ());
Hanoirecursivemethod (number, starting, destination, temp);
}
Public voidHanoirecursivemethod (intNumber ,intStarting,intDestination,inttemp)
{
if( number==1)
Output.append (Starting+"--->"+Destination+"N");
Else
{
Hanoirecursivemethod (number-1, starting,temp,destination);
Output.append (starting+"--->"+destination +"n");
Hanoirecursivemethod (number-1, temp,destination,starting);
}
}
}