Search code examples
javaarrayseclipseimageslick2d

How can I create multiple images in an array in java using a for statement?


I wish to link to the 52 card images to an array, but without adding them individually. I was thinking something like creating an array and using a piece of code something like this.

Image[] card;
card = new int[52];
for (int c = 1; c<=52;c++)
{
    card[c] = 
}  

I'm not sure how to proceed, but the cards in the file are labelled 1-52 so I figured that would be an easier way(and a better way to impress my teacher) to create the card values. I thnk I might also have to change the ranks system and use that as well. I'm using slick2d for the graphics.

How can I use that piece of code(or a different piece of code) to assign the images to a variable?


Solution

  • Check out slick2d javadoc at http://www.slick2d.org/javadoc/ and find the Image class you are trying to use.

    Try this code

    Image[] card = new Image[52];
    for (int i = 0; i < 52; i++)
        {
            card[i] = new Image(/*insert constructors here*/);
        }
    

    If you read the documentation you will find out there are many different ways to create a new image object. e.g. I downloaded an ace of spades image and the following code should create an array of 52 aces of spades

    Image[] card = new Image[52];
    String fileLocation = "C:\\Users\\con25m\\Pictures\\ace_spades.jpg";
    for (int i = 0; i < 52; i++)
        {
            card[i] = new Image(fileLocation);
        }
    

    You can either find out if slick2d has images for all of the cards in a standard 52 deck or download images of each card yourself, come up with a naming convention for the images and then update the fileLocation string in the forloop. e.g.

    Image[] card = new Image[52];
    String fileLocation = new String();
    for (int i = 0; i < 52; i++)
        {
            fileLocation = "C:\\Users\\con25m\\Pictures\\" + i + ".jpg";
            card[i] = new Image(fileLocation);
        }
    

    Note: instead of using the number 52 all of the time consider using a final variable and using that variable instead. e.g.

    final int NUMBER_OF_CARDS = 52;
    Image[] card = new Image[NUMBER_OF_CARDS];
    for (int i = 0; i < NUMBER_OF_CARDS; i++)...