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

2019/6/2

Need help with ArrayList

ChaosPhantom ChaosPhantom

2019/6/2

#
Im trying to select a random item from an Arraylist and then set the image of an actor to the name of the random item that was chosen. This is my method:
1
2
3
4
5
6
7
8
9
10
11
public void setGameScreen()
    {
        while (numCardsHand < 7)
        {
            Card card = new Card();
            card.setImage(cardList.get(cardList.size() + 1) + ".png");
            getWorld().addObject(card, 400, 225);
             
            numCardsHand ++;
        }
    }
I get an error saying cannot find symbol - method size()
danpost danpost

2019/6/2

#
Please show all codes related to cardList in this class.
ChaosPhantom ChaosPhantom

2019/6/2

#
1
String[] cardList = {...};
The"..." is just strings I have in the list
danpost danpost

2019/6/3

#
ChaosPhantom wrote...
1
String[] cardList = {...};
The"..." is just strings I have in the list
Okay -- that is an array (not an arrayList). Use length -- not size().
ChaosPhantom ChaosPhantom

2019/6/3

#
Thanks, but now its saying the same thing for .get() Is it different for Arrays too?
Super_Hippo Super_Hippo

2019/6/3

#
Yes, you don't need to call any methods an arrays. (I think you can't call any methods on arrays at all.) But using the length+1's item in an array won't work because it doesn't exist. Even the length's item doesn't exist. The first item has the index 0 and the last one has the index length-1. (Despite the fact described above, the code would look like this:)
1
card.setImage(cardList[cardList.length+1] + ".png");
ChaosPhantom ChaosPhantom

2019/6/3

#
Alright, thank you! Also, its meant to be
1
Greenfoot.getRandomNumber(cardList.length + 1);
danpost danpost

2019/6/3

#
ChaosPhantom wrote...
Alright, thank you! Also, its meant to be
1
Greenfoot.getRandomNumber(cardList.length + 1);
Remove the '+1'. The last element is indexed one less than the length of the array (since counting starts at zero).
You need to login to post a reply.