2

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.

3
  • what is imageURL String? Commented Dec 6, 2012 at 4:48
  • its the url for the image, I'm not really going to be able to explain it past that because my teacher in class just coded it into one of our templates a while back. Commented Dec 6, 2012 at 5:52
  • @Bhavik Shah imageURL10= cl.getResource((picPath+"choiceGirlBoy.png")); this is just and example of what comes from before this code Commented Dec 6, 2012 at 17:32

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

just change condition to i <= 5
Thanks, this helped A LOT,because quite a bit of my code got reduced as i imported many different images.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.