NU2JAVA
NU2JAVA

Reputation: 1

Towers of Hanoi in Java using stacks

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?

Upvotes: 0

Views: 5664

Answers (1)

Gaurav
Gaurav

Reputation: 12796

So should I create a new hanoi object for each disk based on user input and push them to stack in reverse order?

Yes.

for (int i = numDisc; i > 0; --i)
    tower[0].push(new Hanoi(i));

Upvotes: 1

Related Questions