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

2014/4/11

ArrayList is not adding up

bilzard bilzard

2014/4/11

#
Hi everyone, I am currently busy making my own game as a school project. What I want to achieve is that I add every object that one of my Actors pick-up add up in an ArrayList. My method:
    public void bijhoudenOpgepakteObject()
    {
        
        ArrayList<Munt> muntBrons = new ArrayList();
        ArrayList<Munt> muntZilver = new ArrayList();
        ArrayList<Munt> muntGoud = new ArrayList();  
        

        if (waarde == 3)
        {
            muntGoud.add(this);
            System.out.println(muntGoud.size());
        }
        
        
        
    }
A little translation here: 'munt' means 'coin' and 'waarde' means 'worth/value'. Every coin that is worth 3 point needs to be added to an ArrayList. When I print the ArrayLists size I see that there is 1 entry, but when I pick-up another coin it stays at size 1. This is my Munt.class constructor:
    public Munt(String muntPlaatje, int tijd, int waarde)
    {
        setImage(new GreenfootImage(muntPlaatje));
        this.tijd = tijd;
        this.waarde = waarde;
    }
Does anyone have any idea how I can fix this problem? Thanks in advance. EDIT: If you think there is any missing information, just ask for it and I will post it.
danpost danpost

2014/4/11

#
Every time the 'bijhoudenOpgepakteObject' method is called, you are creating new ArrayLists. Even if you moved them outside the method and made them instance arrays, each coin would have its own set of arrays and still you will only see one added to any one. They must not only be outside the method, but they must also be declared static or moved outside the class entirely (probably best in your world subclass as instance arrays).
bilzard bilzard

2014/4/11

#
Hey danpost, Thanks for the help! It works now! I had a NullPointerException, but after some troubleshooting I forgot to add this:
    public void addedToWorld(World wereld)
    {
        this.wereld = (SpelWereld) wereld;
    }
Thanks again for the help. :-)
You need to login to post a reply.