Exikle
Exikle

Reputation: 1165

Optimizing Java Code Snippet

I;m trying to shorten code on a program I'm coding and the code I need advice on shortening is this part:

imgRunM[0] = toolkit.createImage(imageURL11);
imgRunM[1] = toolkit.createImage(imageURL12);
imgRunM[2] = toolkit.createImage(imageURL13);
imgRunM[3] = toolkit.createImage(imageURL14);
imgRunM[4] = toolkit.createImage(imageURL15);
imgRunM[5] = toolkit.createImage(imageURL16);

I was thinking it could be written as a loop, just not sure how to write it correctly.

I tried this:

for (int x=1; x<7;x++)
  imgRunM[x-1] = toolkit.createImage(imageURL1+x);

It did not error out but when I ran the program, the image did not appear so I'm not really sure what happened.

If anyone has any suggestions I would appreciate it.

Upvotes: 2

Views: 88

Answers (1)

The111
The111

Reputation: 5867

I'd suggest making an array of imageURL's also, instead of having a new variable name for each one. Then you could do this:

for (int i = 0; i <= 5; i++) {
    imgRunM[i] = toolkit.createImage(imageURL[i+11]);
}

Not sure why you have the +11 offset, but I kept it intact.

Upvotes: 2

Related Questions