# What's wrong with my code? (generate sequences of numbers using a stack)

• October 17th, 2012, 11:31 PM
mescoff
What's wrong with my code? (generate sequences of numbers using a stack)
Hi! I am having a small (and possibly really simple) problem with my code (I am using java)...

Here is the assignment given by my teacher:

Use a Stack to write a method allSeqs(int max, int len) that will generate all sequences, consisting of the numbers between 1 and max, of length len. For instance, calling allSeqs(3,2) gives: [1, 1][1, 2][1, 3][2, 1][2, 2][2, 3][3, 1][3, 2][3, 3] while calling allSeqs(2, 4) gives [1, 1, 1, 1][1, 1, 1, 2][1, 1, 2, 1][1, 1, 2, 2][1, 2, 1, 1][1, 2, 1, 2][1, 2, 2, 1][1, 2, 2, 2][2, 1, 1, 1][2, 1, 1, 2][2, 1, 2, 1][2, 1, 2, 2][2, 2, 1, 1][2, 2, 1, 2][2, 2, 2, 1][2, 2, 2, 2]

You can use a backtracking method, very similar to what we did for the N Queens problem: Push the proper number of 1's onto a Stack, and then repeatedly

print out the stack contents (that's one permutation), and
pop the top element, and if it's not equal to max, add one to it, and push it back.

And here is my code:

Code :

```import java.util.*;   public class NewStack {   private Stack<Integer> s;   public String toString() { String result = "[ ";   while ( !s.isEmpty()) result = result + s.pop() + ","; result = result + "]"; return result; }       public void allSeqs(int max, int len) { System.out.println(s);   while (s.size() < len){ s.push(1); } System.out.println(s);   for (int i=0; i<len; i++){ try{   int a = s.pop();   if (a < max) { a = a + 1; s.push(a); } else { s.push(1); } System.out.print(s); }//end try block catch (NullPointerException e) { System.out.println("The last slot has been reached, the next one is empty so, we are done!"); } }//end for loop } //end method       public static void main(String[] args) { NewStack nt = new NewStack();   nt.allSeqs(2,3); } }```

It compiles, but I can't get it to work properly, it gives me a NullPointerException whenever I try to run it...
Do you know what's wrong??

Thank you!
• October 18th, 2012, 01:52 AM
jps
Re: What's wrong with my code? (generate sequences of numbers using a stack)
Quote:

it gives me a NullPointerException whenever I try to run it...
What does it say?
• October 18th, 2012, 09:12 AM
Zaphod_b
Re: What's wrong with my code? (generate sequences of numbers using a stack)
Quote:

Originally Posted by mescoff
...it gives me a NullPointerException ..

The error message has a line number. The statement on that line is, somehow, dereferencing a reference variable that was declared but not initialized in your code. For example, invoking a method of some object where the object was never created.

What is that variable?

Where is it declared?

Where is it initialized? (Note that for a reference variable that is declared but is not explicitly initialized in the declaration statement, it is initialized with a null value.)

Cheers!

Z