汉诺塔的java代码 java编写汉诺塔代码

求JAVA汉诺塔相关的socket代码定义了服务器线程类 , 服务器运行在一个单独的线程中 。
客户端运行在主线程中 。
所有代码放在一个源文件中就行 。源文件名是Hanoi.java
下面是源代码,输入的盘子数不要太大,20以内,否则会步数太多,输出耗时太久 。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Hanoi {
public static void main(String[] args) {
//创建服务器
HanoiServer server = new HanoiServer();
server.start();//启动服务器
/*开始创建客户端*/
Socket socket = null;//客户端Socket
try {
socket = new Socket(InetAddress.getLocalHost(), 8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream printStream = new PrintStream(socket.getOutputStream());
Scanner scanner=new Scanner(System.in);
System.out.println("请输入盘子数(3-10),数字太大,运算时间就会太长可能会卡死 。");
printStream.print(scanner.nextInt());
printStream.println();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
System.out.println("客户端socket关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class HanoiServer extends Thread {//服务器线程类
private ServerSocket serverSocket;
public HanoiServer() {
try {
this.serverSocket = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
private void hanoi(int n, String from, String inter, String to, PrintStream printStream) {
if (n == 1) {
printStream.print("Disk 1 from "from" to "to);
printStream.println();
} else {
hanoi(n - 1, from, to, inter, printStream);
printStream.print("Disk "n" from "from" to "to);
printStream.println();
hanoi(n - 1, inter, from, to, printStream);
}
}
@Override
public void run() {
Socket socket = null;
try {
socket = this.serverSocket.accept();
PrintStream printStream = new PrintStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int n = Integer.parseInt(reader.readLine());
this.hanoi(n, "A", "B", "C", printStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
System.out.println("服务器socket关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
this.serverSocket.close();
System.out.println("服务器serverSocket关闭");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
用JAVA编写一个汉诺塔类要求有 int diskNum,string source, string middle ,string target附录:主要源程序
(1) Disk.java
package code;
import java.awt.*;
public class Disk extends Button {
int number;//盘子的个数
public Disk(int number) {this.number = number;
setBackground(Color.yellow);}
public int getNumber() {return number; }}
(2) TowerPoint.java
package code;
import java.awt.*;
public class TowerPoint {
int x, y;//塔上的点位置,即盘子的放置位置
boolean isHaveDisk;//判断点上是否有盘子
Disk disk ;HannoiTower con ;
public TowerPoint(int x, int y, boolean boo) {this.x = x;this.y = y;isHaveDisk = boo; }
public boolean getIsHaveDisk() {return isHaveDisk; }
public void setIsHaveDisk(boolean boo) {isHaveDisk = boo; }
public int getX() {return x;} //获得点位置坐标
public int getY() {return y;}
public void putDisk(Disk disk, HannoiTower con) {//在点上放盘子
this.con = con;con.setLayout(null);//设置布局
this.disk = disk;con.add(disk);//加盘子到容器中
int w = disk.getBounds().width;//获得盘子的长和宽getBounds()以Rectangle对象的形式获取组件的边界
int h = disk.getBounds().height;
disk.setBounds(x - w / 2, y - h / 2, w, h);//setBounds()移动组件并调整其大小,控件位置坐标,后面是宽度和高度
isHaveDisk = true;con.validate();}
public Disk getDisk() {return disk; }}
(3) HannoiTower.java
package code;
import javax.swing.*;
import java.awt.*;
public class HannoiTower extends JPanel{
TowerPoint point[];//塔上点数组
boolean move = false;//判断是否移动
Disk disks[];//盘子数组
int diskNum = 0;//定义盘子个数
int width, height;//盘子的宽度和高度
char towerName[] = { 'A', 'B', 'C' };//塔名
TextArea infoArea ;
int autoNum = 1;//计算步数
public HannoiTower(int number, int w, int h, char[] name, TextArea text) {towerName = name;diskNum = number;width = w;height = h;
infoArea = text;setLayout(null);
disks = new Disk[diskNum];//初始化盘子个数
//设置塔上的点属性
point = new TowerPoint[3 * diskNum];//塔上点的个数=3*盘子个数
int space = 20;
for (int i = 0; idiskNum; i) {//第一根柱子上的点
point[i] = new TowerPoint(40width, 100space, false);//设置点的位置和没有盘子
space = spaceheight; }
space = 20;
for (int i = diskNum; i2 * diskNum; i) {//第二根柱子上的点
point[i] = new TowerPoint(200width, 100space, false);
space = spaceheight;}
space = 20;
for (int i = 2 * diskNum; i3 * diskNum; i){//第三根柱子上的点
point[i] = new TowerPoint(360width, 100space, false);
space = spaceheight;}
//设置盘子属性
int tempWidth = width;
int sub = (int) (tempWidth / diskNum);
for (int i = diskNum - 1; i = 0; i--) {disks[i] = new Disk(i);
disks[i].setSize(tempWidth, height);//设置盘子的宽和高
tempWidth = tempWidth - sub;}
for (int i = 0; idiskNum; i) {point[i].putDisk(disks[i], this);
}}
public void paint(Graphics g) {super.paint(g);
g.drawLine(point[0].getX(), point[0].getY(), point[diskNum - 1].getX(),point[diskNum - 1].getY());//画3根竖线
g.drawLine(point[diskNum].getX(), point[diskNum].getY(),
point[2 * diskNum - 1].getX(), point[2 * diskNum - 1].getY());
g.drawLine(point[2 * diskNum].getX(), point[2 * diskNum].getY(),
point[3 * diskNum - 1].getX(), point[3 * diskNum - 1].getY());
g.drawLine(point[diskNum - 1].getX() - width,
point[diskNum - 1].getY(), point[3 * diskNum - 1].getX()
width, point[3 * diskNum - 1].getY());
int leftx = point[diskNum - 1].getX() - width;//画灰色矩形
int lefty = point[diskNum - 1].getY();
int w = (point[3 * diskNum - 1].getX()width) - (point[diskNum - 1].getX() - width);
int h = height / 2;
g.setColor(Color.gray);
g.fillRect(leftx, lefty, w, h);
g.setColor(Color.red);//画红点
int size = 4;
for (int i = 0; i3 * diskNum; i) {
g.fillOval(point[i].getX() - size / 2, point[i].getY() - size / 2, size, size); }
g.drawString(""towerName[0]"塔", point[diskNum - 1].getX(),
point[diskNum - 1].getY()30);
g.drawString(""towerName[1]"塔", point[2 * diskNum - 1].getX(),
point[diskNum - 1].getY()30);
g.drawString(""towerName[2]"塔", point[3 * diskNum - 1].getX(),
point[diskNum - 1].getY()30);
g.drawString("将全部盘子从"towerName[0]"塔搬运到"towerName[1]"塔"towerName[2]"塔", point[diskNum - 1].getX(),point[diskNum - 1].getY()80);}
/**
* 自动演示函数
*/
public void autoMoveDisk(int diskNum, char one, char two, char three) {//one塔1、two塔2、three塔3
if (diskNum == 1) //当盘子只有一个时
{infoArea.append(autoNum":"one"塔 -----"three"塔\n");
autoNum;
Disk disk = getTopDisk(one);//获得塔1上最上面的盘子
int startI = getTopDiskPosition(one);//
int endI = getTopDiskUp(three);
if (disk != null) {point[endI].putDisk(disk, this);
point[startI].setIsHaveDisk(false);pause();}}
else {autoMoveDisk(diskNum - 1, one, three, two);
infoArea.append(autoNum":"one"塔 -----"three"塔\n");
autoNum;
Disk disk = getTopDisk(one);
int startI = getTopDiskPosition(one);
int endI = getTopDiskUp(three);
if (disk != null) {point[endI].putDisk(disk, this);
point[startI].setIsHaveDisk(false);pause();}
autoMoveDisk(diskNum - 1, two, one, three);}}
/**
* 取最上方的盘子
*/
public Disk getTopDisk(char towerN) {//towerN塔名
Disk disk = null;
if (towerN == towerName[0]) {
for (int i = 0; idiskNum; i) {
if (point[i].getIsHaveDisk() == true) {//判断是否有盘子
disk = point[i].getDisk();break;}}}
if (towerN == towerName[1]) {
for (int i = diskNum; i2 * diskNum; i) {
if (point[i].getIsHaveDisk() == true) {
disk = point[i].getDisk();break;}}}
if (towerN == towerName[2]) {
for (int i = 2 * diskNum; i3 * diskNum; i) {
if (point[i].getIsHaveDisk() == true) {
disk = point[i].getDisk();break;}}}
return disk;}
/**
* 在塔中获取盘子的放置位置
*/
public int getTopDiskUp(char towerN) {
int position = 0;
if (towerN == towerName[0]) {
int i = 0;
for (i = 0; idiskNum; i) {
if (point[i].getIsHaveDisk() == true) {
position = Math.max(i - 1, 0);
break;}}
if (i == diskNum) {position = diskNum - 1; }}
if (towerN == towerName[1]) {
int i = 0;
for (i = diskNum; i2 * diskNum; i) {
if (point[i].getIsHaveDisk() == true) {
position = Math.max(i - 1, 0);break;}}
if (i == 2 * diskNum) {position = 2 * diskNum - 1; }}
if (towerN == towerName[2]) {int i = 0;
for (i = 2 * diskNum; i3 * diskNum; i) {
if (point[i].getIsHaveDisk() == true) {
position = Math.max(i - 1, 0);break;}}
if (i == 3 * diskNum) {position = 3 * diskNum - 1; }}
return position;}
/**
* 在塔中获取最上面盘子的位置
*/
public int getTopDiskPosition(char towerN) {
int position = 0;
if (towerN == towerName[0]) {
int i = 0;
for (i = 0; idiskNum; i) {
if (point[i].getIsHaveDisk() == true) {
position = i;break;}}
if (i == diskNum) {position = diskNum - 1; }}
if (towerN == towerName[1]) {int i = 0;
for (i = diskNum; i2 * diskNum; i) {
if (point[i].getIsHaveDisk() == true) {position = i;break;}}
if (i == 2 * diskNum) {position = 2 * diskNum - 1; }}
if (towerN == towerName[2]) {int i = 0;
for (i = 2 * diskNum; i3 * diskNum; i) {
if (point[i].getIsHaveDisk() == true) {
position = i;break;}}
if (i == 3 * diskNum) {position = 3 * diskNum - 1; }}
return position;}
public void pause() {
try {Thread.sleep(1000);// 1s移动1步} catch (InterruptedException e) {}}}
(4) Tower.java
package code;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Tower extends Frame implements ActionListener, ItemListener, Runnable {
HannoiTower tower;
JButton renew, auto;
Choice diskNumComBox;
char towerName[] = { 'A', 'B', 'C' };
int diskNum, diskWidth, diskHeight;
Thread thread;
TextArea infoArea;
public Tower() {
thread = new Thread(this);
diskWidth = 120;diskHeight = 18;
infoArea = new TextArea(15, 15);
infoArea.setText(null);
diskNumComBox = new Choice();//下拉列表
diskNumComBox.setName("diskNumComBox");//设置名字
diskNumComBox.setSize(300, 10);//设置列表大小
diskNumComBox.setFont(new java.awt.Font ("Dialog", 0, 11));//设置字体
diskNumComBox.setBackground(java.awt.Color.white);//设置下拉按钮的背景色
diskNumComBox.setForeground(java.awt.Color.black);//设置下拉按钮的前景色
for(int i=1;i=9;i){diskNumComBox.add(String.valueOf(i));}//设置盘子数目
diskNum = Integer.valueOf(diskNumComBox.getSelectedItem().toString());
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
renew = new JButton("重新开始");
auto = new JButton("自动演示");
renew.addActionListener(this);
auto.addActionListener(this);
diskNumComBox.addItemListener(this);
JPanel topPanel = new JPanel();//设置两个按钮和下拉按钮的布局,放于容器topPanel中
topPanel.add(auto, BorderLayout.WEST);
topPanel.add(renew, BorderLayout.CENTER);
topPanel.add(diskNumComBox, BorderLayout.EAST);
add(tower, BorderLayout.CENTER);//设置整体布局为边界布局
add(topPanel, BorderLayout.NORTH);
add(infoArea, BorderLayout.EAST);
addWindowListener(new WindowAdapter() {//关闭窗口时调用
public void windowClosing(WindowEvent e) {
System.exit(0);}});
setVisible(true);setBounds(40, 20, 700, 540);
validate();//是Container类中的方法,该方法用来更新容器中的布局}
public void actionPerformed(ActionEvent e) {//重置
if (e.getSource() == renew) {
if (!(thread.isAlive())) {//判断线程不活着
this.remove(tower);//Frame中的函数,重新构建,从此窗体移除指定的菜单栏 。
infoArea.setText(null);
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
add(tower, BorderLayout.CENTER);
validate();}
else {}}
if (e.getSource() == auto) {//创建线程,自动演示
if (!(thread.isAlive())) {thread = new Thread(this); }
try {thread.start();} catch (Exception eee) {}}}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == diskNumComBox) {
if (!(thread.isAlive())) {
this.remove(tower);
infoArea.setText(null);
diskNum = Integer.valueOf(diskNumComBox.getSelectedItem().toString());
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
add(tower, BorderLayout.CENTER);
validate();}
else {}}}
public void run() {
this.remove(tower);
infoArea.setText(null);
tower = new HannoiTower(diskNum, diskWidth, diskHeight, towerName, infoArea);
add(tower, BorderLayout.CENTER);validate();
tower.autoMoveDisk(diskNum, towerName[0], towerName[1], towerName[2]);}
public static void main(String args[]) {
new Tower();}}
求一个汉诺塔的JAVA代码public class Hannoi {
public static void main(String[] args) {
int nDisks = 3;
moveDish(nDisks, 'A', 'B', 'C');
}
private static void moveDish(int level, char from, char inter, char to) {
if (level == 1) {
System.out.println("从"from"移动盘子 "level" 号到"to);
} else {
moveDish(level - 1, from, to, inter);
System.out.println("从"from"移动盘子 "level" 号到"to);
moveDish(level - 1, inter, from, to);
}
}
}
java实现汉诺塔的代码,求注释 , 具体到每一行代码,急求, , , 这样应该可以了
如果还有那个地方不懂的,建议你研究下汉诺塔算法
import
java.io.BufferedReader;//引入IO包中的BufferedReader
import
java.io.IOException;//引入IO包中的IO异常处理
import
java.io.InputStreamReader;//引入IO包中的InputStreaReader
public
class
Hinoi
{
//主类
static
int
m=0;//定义移动的次数
//主程序入口--main方法
public
static
void
main(String[]
args)
{
//创建BufferedReader对象,InputStream输入流
BufferedReader
bf
=
new
BufferedReader(new
InputStreamReader(System.in));
System.out.println("请输入盘子的个数:");
try
{
int
sl
=
Integer.parseInt(bf.readLine().toString());//接收总盘子个数
toMove(sl,"A","B","C");//调用移动方法
A--C
}
catch
(NumberFormatException
e)
{捕获NumberFormatException异常
//
TODO
Auto-generated
catch
block
e.printStackTrace();//打印异常
}
catch
(IOException
e)
{//捕获IOException异常
//
TODO
Auto-generated
catch
block
e.printStackTrace();//打印异常
}
System.out.println("总共移动了:" m "
次数");//打印移动次数
}
//移动方法
private
static
void
toMove(int
sl,
String
one,
String
two,String
three)
{
if(sl==1){//如果只有一个盘子,则直接移动到C柱
System.out.println("盘子" sl "

" one "----" three);
}else{//如果总盘数大于1 , 则递归调用移动方法
//把所有的数量为sl-1的盘子全部从A移到到B(C作为一个过渡),好提供一个最下面的位置给最大盘子到C;
toMove(sl-1,one,three,two);
System.out.println("盘子" sl "

" one "----" three);
//把所有的剩余的盘子从B移动到C(A作为一个过渡)
toMove(sl-1,two,one,three);
}
m;
}
}
怎样用Java编写汉诺塔程序package Hanoi;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
public class Hanoi {
public static void main(String args[]) throws IOException {
Hanoi aa = new Hanoi();
aa.go();
}
public void go() throws IOException {
int n;
BufferedReader buf;
buf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入盘数汉诺塔的java代码:");
n = Integer.parseInt(buf.readLine());
Hanoi hanoi = new Hanoi();
hanoi.move(n, 'A', 'B', 'C');
}
public void move(int n, char a, char b, char c) {
if (n == 1) {
System.out.println("盘 "n" 由 "a" 移至 "c);
} else {
move(n - 1, a, c, b);
System.out.println("盘 "n" 由 "a" 移至 "c);
move(n - 1, b, a, c);
}
}
}
用java实现汉诺塔的程序是啥呀?其实不知道你到底是想要代码还是要什么
给你帖的示范代码吧:
汉诺塔问题的递归Java语言实现
public
class
Hanoi
{/**
*
*
@param
n
*
盘子的数目
*
@param
origin
*
源座
*
@param
assist
*
辅助座
*
@param
destination
*
目的座
*/
public
void
hanoi(int
n,
char
origin,
char
assist,
char
destination)
{
if
(n
==
1)
{
move(origin,
destination);
}
else
{
hanoi(n
-
1,
origin,
destination,
assist);
move(origin,
destination);
hanoi(n
-
1,
assist,
origin,
destination);
}
}
//
Print
the
route
of
the
movement
private
void
move(char
origin,
char
destination)
{
System.out.println("Direction:"
origin
"---"
destination);
}
public
static
void
main(String[]
args)
{
Hanoi
hanoi
=
new
Hanoi();
hanoi.hanoi(3,
'A',
'B',
'C');
}
}
【汉诺塔的java代码 java编写汉诺塔代码】关于汉诺塔的java代码和java编写汉诺塔代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息 , 记得收藏关注本站 。

    推荐阅读