0

I am getting a NullPointerException in the hanoi function when pushing the values from the input into the stack and I'm not sure why heres my code:

public class Hanoi {

public static Stack<Integer>[] towersOfHanoi = new Stack[4];
static int moves;

public static void hanoi(int n) {

    for(int i = n; n > 0; i--) {
        towersOfHanoi[1].push(i);
    }

    moveDisc(n, 1, 2, 3);
}

public static void moveDisc(int n, int j, int k, int l) {

    moveDisc(n-1, j, k, l);
    int i = towersOfHanoi[j].pop();
    towersOfHanoi[k].push(i);
    moves++;
    moveDisc(n-1, l, j, k);
}

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);

    System.out.println("Enter number of discs: ");
    int n = in.nextInt();
    in.close();

    hanoi(n);

    towersOfHanoi[1] = new Stack<Integer>();
    towersOfHanoi[2] = new Stack<Integer>();
    towersOfHanoi[3] = new Stack<Integer>();

    System.out.println(moves);
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
  • You call `hanoi(n);` before `towersOfHanoi[1] = new Stack();`, this means that when `hanoi` is executed, each element in the array is `null`. Also, Java arrays are zero indexed, so you might want to be aware of that – MadProgrammer Aug 08 '18 at 01:55

1 Answers1

0

You've initialized an array of Stacks, but you haven't actually allocated Stacks and put them in said Array. In your main() function, you should do something like:

for (int i = 0; i < 4; i++)
{
  towersOfHanoi[i] = new Stack<Integer>();
}

Edit: Do this BEFORE you call hanoi(n). Otherwise, you're referencing objects before allocating them.

WestaAlger
  • 501
  • 3
  • 12
  • Yeah but he wasn't doing it before calling `hanoi` where all the references are – WestaAlger Aug 08 '18 at 01:47
  • There seem to be other potentially bigger problems than this, for example I don't see any logic present to stop the recursive calls. – Tim Biegeleisen Aug 08 '18 at 01:49
  • Weeelll, the OP is, `towersOfHanoi[1] = new Stack();`, but isn't doing it at the right point in the codes execution, not to mention they don't seem to understand that arrays are zero indexed :| – MadProgrammer Aug 08 '18 at 01:53
  • Wait you're right lol. Doesn't look like the code is zero-indexed............. :| – WestaAlger Aug 08 '18 at 02:04