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

2019/6/16

Iterating the Name of a Variable

MRCampbell MRCampbell

2019/6/16

#
I am trying to create animation and have several images with similar name. (explosion0, explosion 1, ..., explosion8) . I want to concatenate a variable name so I don't need 8 if statements. Instance Variables
private GreenfootImage explosion0;
private GreenfootImage explosion1;
...
private GreenfootImage explosion8;
private int timer;
private int imageCounter;
In the Constructor
explosion0 = new GreenfootImage("Explosion0.png");
explosion1 = new GreenfootImage("Explosion1.png");
...
explosion8 = new GreenfootImage("Explosion2.png");
the code
if(timer == 5)
        {
            String imageName = "explosion" + imageCounter;
            setImage(imageName);
            imageCounter = imageCounter + 1;
            timer = 0;
        }
timer = timer + 1;
Nosson1459 Nosson1459

2019/6/16

#
use an array
private GreenfootIImage[] explosion=new GreenfootIImage [9];
//I used 9 because you started your variable count from zero and went to eight which actually comes out to nine variables
MRCampbell MRCampbell

2019/6/16

#
Can you elaborate a little more on how I would implement this? Also wouldn't an array also start at 0? Was the second "I" in GreenfootIImage a mistake?
Super_Hippo Super_Hippo

2019/6/16

#
The number 9 represents the number of values in the array, not the highest index. Yes, the II was one I too much in there. (And nice copy&paste probably.) :P You can either use:
private static GreenfootImage[] images = new GreenfootImage[9];

static
{
    for (int i=0; i<9; i++) images[i] = new GreenfootImage("Explosion"+i+".png");
}
or:
private static GreenfootImage[] images =
{
    new GreenfootImage("Explosion0.png"),
    new GreenfootImage("Explosion1.png"),
    new GreenfootImage("Explosion2.png"),
    new GreenfootImage("Explosion3.png"),
    new GreenfootImage("Explosion4.png"),
    new GreenfootImage("Explosion5.png"),
    new GreenfootImage("Explosion6.png"),
    new GreenfootImage("Explosion7.png"),
    new GreenfootImage("Explosion8.png")
};
The first one is a little bit more elegant in my eyes. Then you can easily use a variable to set the image.
setImage(imageCounter);
You need to login to post a reply.