⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 towersofhanoi.java

📁 Java做的汉诺塔
💻 JAVA
字号:
/*
 * Created on 2006-1-1
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author webb
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
//Lab 3: TowersOfHanoi.java 
//Program solves the Towers of Hanoi problem 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class TowersOfHanoi 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 ); 
/* Write code that creates a JScrollPane and attach outputArea to it */ 
//outputArea.setText( output ); 
JScrollPane scroll = new JScrollPane(outputArea); 

//add components to applet 
Container container = getContentPane(); 
container.setLayout( new FlowLayout() ); 
/* Write code to add the components to the content pane */ 
input.addActionListener(this); 

container.add(label); 
container.add(input); 
container.add(scroll); 

} 

//recusively move disks through towers 
/* write header for method tower */ 
String tower(int n,String peg1,String peg2,String 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) 
return 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 
{ 
tower(n-1,peg1,peg3,peg2); 


//move last disk from peg1 to peg3 recursively 
output += "\n" + peg1 + " --> " + peg3; 

//move ( disks - 1 ) disks from peg2 to peg3 recursively 
/* Write a recursive call to method tower that moves 
( disks - 1 ) disks from peg2 to peg3 */ 
tower(n-1,peg2,peg1,peg3); 
return output; 

} 
} 

//actually sort the number of discs specified by user 
public void actionPerformed( ActionEvent e ) 
{ 
output = ""; 

/* 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 */ 
int n=Integer.parseInt(input.getText()); 
String peg1="1"; 
String peg2="2"; 
String peg3="3"; 
output+=tower(n,peg1,peg2,peg3); 

outputArea.setText( output ); 
} 

} // end class TowersOfHanoi 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -