0

I have a class Floor which has a Stack of Blocks and I don't know how to initialize it. I had tried like this:

public class Floor {
    private Stack<Block> stack;
    private static int size;
    public void setStack(Stack<Block> stack) {
        this.stack = stack;
    }
    public void addBlock(Block b){
        stack.push(b);
    }
}

public class InputDevice {
    Block a0=new Block('I',false);
    Floor [] floor=new Floor[5];
    Stack<Block> stack=new Stack<Block>();
    floor[0].setStack(stack);
    floor[0].addBlock(a0);
}
1
  • 1
    Why are you using the static modifier for the size field? Commented Jan 12, 2013 at 11:36

3 Answers 3

5
Floor [] floor=new Floor[5];

you declared the array, but you didn't init the elements, then :

floor[0].setStack(stack); floor[0] is null, npe!

also I suggest that in your Floor class, addBlock(Block b) method, check if the stack is null, if it is null, otherwise it would have problem(NPE) if someone init Floor, and directly floor.addBlock(b).

Sign up to request clarification or add additional context in comments.

Comments

2

You've not initialized any of the Floor objects in the array yet. When you create an array of objects it's like creating an egg carton. You can't use any eggs until you put some in the carton first. You can't use any objects in the array before you've initialized them, which is often done within a for loop. i.e.,

Floor [] floor=new Floor[5];
for (int i = 0; i < floor.length; i++) {
  floor[i] = new Floor();
}

2 Comments

Thank you! I thought that by new Floor[5] I was creating 5 Floor objects when I actually had just a pointer to a 5 Floor memory space.
@AlexandruCimpanu: exactly! The other metaphor I like to use is that of a likening an array to a parking lot. You first have to fill it with cars to be able to drive one.
0

try this code

public class Floor {
    private Stack<Block> stack;
    private static int size;
    public void setStack(Stack<Block> stack) {
        this.stack = stack;
    }
    public void addBlock(Block b){
        stack.push(b);
    }
}

public class InputDevice {
    Block a0=new Block('I',false);
    Floor [] floor=new Floor[5];
    floor[0] = new Floor();
    Stack<Block> stack=new Stack<Block>();
    floor[0].setStack(stack);
    floor[0].addBlock(a0);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.