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

2014/5/11

List help.

Jonche Jonche

2014/5/11

#
Hello, I've got a nullPointerException and I don't understand why. This is the place where the error is :
if(stats == 0){items.add(items.size()+1,1);}
the int fiels stats is equal to 0, the items field is an Integer List. It is not initialized, or initialized to Null. Thank you for your help
danpost danpost

2014/5/11

#
The 'add(element)' method will always add the element at the end of the list. You should be able to just use:
if(stats == 0) { items.add(1); }
But you must first initialize the List object with something like this:
java.util.List<Integer> items = new java.util.ArrayList();
Jonche Jonche

2014/5/11

#
Thank you, it worked. I didn't know how to initialize the List, I tried new ArrayList(); but it didn't work, now I know why. Thank you. One more thing. How can I set a value to null for example for an Integer field? I tried it like this :
selectedPrimaryWeapon = null;
but it didn't work
danpost danpost

2014/5/11

#
Jonche wrote...
One more thing. How can I set a value to null for example for an Integer field? I tried it like this :
selectedPrimaryWeapon = null;
but it didn't work
Is 'selectedPrimaryWeapon' an Integer field or an 'int' field? If it is an 'int' field, you cannot set it to 'null', being 'int' is one of the primary data types. Object references can be 'null', so I as an 'Integer' type, you should be able to set it to 'null':
Integer numberObject = null;
Jonche Jonche

2014/5/11

#
Oh well, I think I misunderstood my error, I believe I am comparing the Integer with an int value in an "If" statement. There is my error :
if(selectedPrimaryWeapon == selectedItem)
Is there a way to compare these two values? (selectedPrimaryWeapon is an Integer field and selectedItem is an int field)
danpost danpost

2014/5/11

#
If you had looked at what methods were available for Integer objects (Integer API documentation), you might have found that you could use:
if (selectedPrimaryWeapon.intValue() == selectedItem);
Jonche Jonche

2014/5/11

#
It still does not work, I do believe I missed something. That's the code part that gives me a nullPointerException :
if(selectedPrimaryWeapon.intValue() == selectedItem){selectedPrimaryWeapon = null;}
I might not have initialised it correctly because I didn't at all for I want it to be null.
Jonche Jonche

2014/5/11

#
Fixed it. I did a double condition :
if(selectedPrimaryWeapon !=null && selectedPrimaryWeapon.intValue() == selectedItem){selectedPrimaryWeapon = null;}
danpost danpost

2014/5/11

#
You also could have used:
if ((new Integer(selectedItem)).equals(selectedPrimaryWeapon))
You need to login to post a reply.