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

2016/1/6

getting an error java.util.ArrayList cannot be cast to Bar

hoothoot hoothoot

2016/1/6

#
Hi, I'm using Danpost's Progress bar code for a school project and I would like to know how to fix this code so I don't get this error. here is the code for my method that is having a problem:
    public void setBar()
    {
        Bar bar = (Bar) getWorld().getObjectsAt(125, 25, Bar.class);
        bar.setValue(getHealth());
}
thanks
danpost danpost

2016/1/6

#
The problem is that 'getObjectsAt' returns a List object. The elements of the list are Bar objects (the list itself is not a Bar object). You cannot assign a List object to a variable that is defined to hold a Bar object. Now, it may be always true that one Bar object will be contained within the List (that a Bar object is located at the position (125, 25) in the world). If there is any chance that no Bar object may be listed, then you must make sure that the List is not empty (or that its size is greater than zero). Once you are sure the List object contains at least one Bar object, you can get a reference to it with this:
Bar bar = (Bar)getWorld().getObjects(125, 25, Bar.class).get(0);
The 'get' method returns the Bar object whose index within the List object is zero (the first element).
hoothoot hoothoot

2016/1/6

#
oh yeah,i just forgot that last part. I knew it, just forgot to type it. thanks.
You need to login to post a reply.