This site requires JavaScript, please enable it in your browser!
Greenfoot back
JoNoBert
JoNoBert wrote ...

2015/6/5

Why do I get a nullPointerException here?

JoNoBert JoNoBert

2015/6/5

#
I have no Idea why I always get a nullPointerException when I use this method. "inv" is an array used for an inventory, first all fields are empty. The fields can be filled with different Items, Key is a subclass of Item. The door only should open if there is a key in the inventory.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if(getOneObjectAtOffset(-1,0,Door.class)!=null && Greenfoot.isKeyDown("o"))
        {
            Door door = (Door)getOneObjectAtOffset(-1,0,Door.class);
            for(int i =0; i<8; i++)
            {
                Item a = inv.give(i);
                if(a.getClass() != null)
                {
                    if(a.getClass()==Key.class && door.open()==false)
                    {
                        door.open();
                    }
                }
            }
        }
I would be happy if someone could help me :D. Thanks
davmac davmac

2015/6/5

#
"inv" is an array used for an inventory
If 'inv' is an array, line 6 would cause a compilation error. Arrays do not have a 'give' method. Is it possible you meant that it's an ArrayList? However, there is still no 'give' method; you would use 'get'.
I have no Idea why I always get a nullPointerException when I use this method.
It would help if you would say which line of code generates the exception. Have you intialised 'inv'? Or perhaps 'inv' contains null elements, so 'a' becomes null which would cause an exception on line 7?
JoNoBert JoNoBert

2015/6/6

#
thanks for answering davmac. the problem is solved now, it really was the problem in line 7, sorry that i didn't wrote the line. I just had to leave away the ".getClass()" so now it works. PS: the give method was not the problem, I just forgot to say that I created it myself. Thank you for helping
You need to login to post a reply.