Java 中使用堆栈的河内塔
我正在编写一个程序,用 Java 玩河内塔游戏。我们将使用堆栈来代表塔。我有一个由 3 个堆栈组成的数组,其中两个堆栈初始化为空,最后一个堆栈填充了用户定义数量的光盘。我有一个 Hanoi 类文件,因此我们可以使用 Hanoi 构造函数,它接受一个整数并创建该大小的光盘。我无法在初始化方法中找出将光盘推入堆栈的代码(它们的大小是其位置的镜像,因此光盘 1 的大小为 1 等)。如有任何帮助,我们将不胜感激。
这是我的 Hanoi 类光盘构造函数:
public class Hanoi{
private int discSize; //size (radius) of the disc
public Hanoi(int size){ //creates a disk of the specifed size
discSize = size;
}
以及我的初始化方法
public static Stack<Hanoi>[] initialize(int n){
System.out.println("How many discs in the game?");
Scanner sc = new Scanner(System.in);
int numDisc = sc.nextInt();
int size = numDisc;
Stack<Hanoi>[] tower = new Stack[3];
for (int i = 0; i < 3;i++){
tower[i] = new Stack<Hanoi>();
}
}
Hanoi.PrintStacks(tower);
// System.out.println(hanoi[2].peek());
return tower;
这应该将它们全部初始化为空。那么我应该根据用户输入为每个磁盘创建一个新的 Hanoi 对象,并将它们以相反的顺序推送到堆栈吗?
I am writing a program to play the towers of Hanoi game in Java. We are to using stacks to represent the towers. I have an array of 3 stacks two of which I initialize to be empty and the last one to be filled with a user defined amount of discs. I have a Hanoi class file that was given so we can use the Hanoi constructor which takes in an integer and creates a disc of that size. I am having trouble figuring out the code to push the discs onto the stack in my initialize method(their size is a mirror of their position so disc 1 is of size 1 etc.) Any help at all would be appreciated.
Here is my Hanoi class disc constructor :
public class Hanoi{
private int discSize; //size (radius) of the disc
public Hanoi(int size){ //creates a disk of the specifed size
discSize = size;
}
And my initialize method
public static Stack<Hanoi>[] initialize(int n){
System.out.println("How many discs in the game?");
Scanner sc = new Scanner(System.in);
int numDisc = sc.nextInt();
int size = numDisc;
Stack<Hanoi>[] tower = new Stack[3];
for (int i = 0; i < 3;i++){
tower[i] = new Stack<Hanoi>();
}
}
Hanoi.PrintStacks(tower);
// System.out.println(hanoi[2].peek());
return tower;
This should initialize all of them to be empty. So should I create a new Hanoi object for each disk based on user input and push them to stack in reverse order?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。
Yes.