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

2015/1/11

Adding values of the array?

elementa elementa

2015/1/11

#
Hi, So I have this array
String [] values = {"2", "3", "5", "8", "13", "21", "34", "55", "89", "144" };
that I would like to be able to add to my DisplayText image whenever one of my door(image)s are pressed. How would I be able to do this? The code for my DisplayText image is this:
private String begin = " 1, 1";
    GreenfootImage displaytext = new GreenfootImage (begin, 25, Color.BLACK, Color.WHITE);
    public void act()
    {
       setImage (displaytext);
    }
danpost danpost

2015/1/11

#
First thing, I do not see any place where you are actually changing the image. Line 2 assigns an image to the field 'displaytext' and line 5 continuously sets that image to the DisplayText object (the assignment of the image to the field is done once when the DisplayText object is created). Second thing, The image does not have to be continuously set in the act method. In fact, the DisplayText object does not have any actions to perform -- it just sits there in the world displaying its image, not doing anything in particular. The only time any changes occur to it is when a door is pressed, which causes its image to change. So, instead of an act method, better would be an update method which would build the string and create a new image to display:
public void update()
{
    begin += ", "+values[/* next */];
    setImage(new GreenfootImage(begin, 25, null, Color.BLACK, Color.WHITE));
}
Now, as you did not say were your array was located, or give any information about accessing it, I treated it as if it was in the DisplayText class. Also, '/* next */' should probably be a counter value that is incremented at the end of the updating. Now, having the door, when pressed, make the DisplayText object update is for a future post. Getting the DisplayText object performing properly should be completed first. You should be able to right click on the object and select 'void update()' to test it.
You need to login to post a reply.