当前位置:编程学习 > JAVA >>

JAVA汉诺塔问题

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TowerOfHanoi extends JApplet implements ActionListener {
   JLabel label;
   JTextField input;
   JTextArea outputArea;
   String output;
   

   public void init()
   {
      output = "";

      // create components
      label = new JLabel( "Enter number of disks ( 1-9 ): " );
      input = new JTextField( 5 );
      input.addActionListener( this );
      outputArea = new JTextArea( 15, 20 );
      Container container = getContentPane();
      container.setLayout( new FlowLayout() );
      /* Write code that creates a JScrollPane and attach outputArea to it */
      JScrollPane scroller=new JScrollPane(outputArea);
      container.add(scroller);
      
      
      outputArea.setText( output );
      
      
      
      
      // add components to applet
     
      /* Write code to add the components to the content pane */ 
      container.add(label);
      container.add(input);
      container.add(outputArea);
     
      
      
   }

   // recusively move disks through towers
   /* write header for method tower */
   public void HANOI(int n,int peg1, int peg2, int peg3){
      /* Write code here that tests for the base case (i.e., one disk). 
         In this case, move the last disk from peg 1 to peg 3 and return. */
      if(n==1)
       output += "\n" + peg1 + " --> " + peg3;
      // move ( disks - 1 ) disks from peg1 to peg2 recursively
      /* Write a recursive call to method tower that moves 
         ( disks - 1 ) disks from peg1 to peg2 */
      else{
       HANOI(n-1,peg1, peg3,peg2);
       output += "\n" + peg1 + " --> " + peg3;
       HANOI(n-1,peg2, peg1,peg3);
      }
      
   }

   // actually sort the number of discs specified by user
   public void actionPerformed( ActionEvent e )
   {
      output = "";
      output+="Result:";
      String t=e.getActionCommand();
      HANOI(Integer.parseInt(t),1,2,3);
      

      /* call method tower and pass it the number input by the user,
         a starting peg of 1, an ending peg of 3 and a temporary peg of 2 */
      

      outputArea.setText( output );    
   }

} // end class TowersOfHanoi

怎样添加代码程序应(在可滚动的JtextArea中)显示将盘子从其起始柱子移动到目标柱子的准确指令。
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,