您的位置:

汉诺塔java,汉诺塔Java课程设计

本文目录一览:

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编写一个汉诺塔类要求有 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; i diskNum; i++) {//第一根柱子上的点

point[i] = new TowerPoint(40 + width, 100 + space, false);//设置点的位置和没有盘子

space = space + height; }

space = 20;

for (int i = diskNum; i 2 * diskNum; i++) {//第二根柱子上的点

point[i] = new TowerPoint(200 + width, 100 + space, false);

space = space + height; }

space = 20;

for (int i = 2 * diskNum; i 3 * diskNum; i++){//第三根柱子上的点

point[i] = new TowerPoint(360 + width, 100 + space, false);

space = space + height; }

//设置盘子属性

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; i diskNum; 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; i 3 * 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; i diskNum; i++) {

if (point[i].getIsHaveDisk() == true) {//判断是否有盘子

disk = point[i].getDisk();break;}}}

if (towerN == towerName[1]) {

for (int i = diskNum; i 2 * diskNum; i++) {

if (point[i].getIsHaveDisk() == true) {

disk = point[i].getDisk();break;}}}

if (towerN == towerName[2]) {

for (int i = 2 * diskNum; i 3 * 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; i diskNum; 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; i 2 * 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; i 3 * 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; i diskNum; 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; i 2 * 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; i 3 * 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新手汉诺塔问题最终的输出结果如下(问题规模为3),其中盘子的编号是汉诺塔问题中从上到下的顺序。

try..catch用于捕获initProperties()和init()这两个方法执行时候的异常,至于initProperties()和init()这两个方法为何会出异常,就看你具体的业务逻辑了。

try中的代码块儿如果一旦出现异常则在catch中进行捕获,showMessageDialog是JOptionPane封装或者说提供的一个显示一个带有确定按钮的模态对话框的方法。

几个参数中

"Failed to init.\n" + ex 也就是第二个参数是消息框弹出消息的内容。

"BinaryRain 也就是第三个参数是消息框的标题。

JOptionPane.ERROR_MESSAGE 也就是第四个参数,是消息框的类型,表示错误提示,弹出来的消息框有个红色的叉叉标识,如JOptionPane.WARNING_MESSAGE,表示警告提示,弹出来的消息框有个叹号标识。

Java汉诺塔的问题

import java.util.LinkedList;

public class Hanoi {

    private int num;

    private Peg[] pegs = new Peg[3];

    public Hanoi(int num) {

        this.num = num;

        pegs[0] = new Peg("A");

        pegs[1] = new Peg("B");

        pegs[2] = new Peg("C");

        for (int i = num; i  0; i--) {

            pegs[0].pushDown(new Plate(i));

        }

    }

    public void start() {

        multiMove(pegs[0], pegs[2], pegs[1], num);

    }

    /**

     * Move a given number plates from one peg to another

     * @param from from this peg

     * @param to to this peg

     * @param temp the temp peg to use

     * @param count how many plates to move

     */

    public void multiMove(Peg from, Peg to, Peg temp, int count) {

        if (count == 1) {

            move(from, to);

            return;

        }

        multiMove(from, temp, to, count - 1);

        move(from, to);

        multiMove(temp, to, from, count - 1);

    }

    public void move(Peg from, Peg to) {

        Plate p = from.popUp();

        to.pushDown(p);

        System.out.print("Moving " + p.size + " from " + from.name + " to " + to.name + "      ");

        printPegs();

    }

    public void printPegs() {

        System.out.println(pegs[0].name + ": " + pegs[0] +

                "    " + pegs[1].name + ": " + pegs[1] +

                "    " + pegs[2].name + ": " + pegs[2]);

    }

    public static class Plate {

        int size;

        Plate(int size) {

            this.size = size;

        }

        @Override

        public String toString() {

            return String.valueOf(size);

        }

    }

    public static class Peg {

        LinkedListPlate plateList = new LinkedList();

        String name;

        public Peg(String name) {

            this.name = name;

        }

        public void pushDown(Plate p) {

            plateList.push(p);

        }

        public Plate popUp() {

            return plateList.pop();

        }

        @Override

        public String toString() {

            return plateList.toString();

        }

    }

    public static void main(String[] args) {

        Hanoi game = new Hanoi(3);

        game.printPegs();

        game.start();

    }

}

用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');

}

}