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

2017/4/11

Problems with an ArrayList

vermox vermox

2017/4/11

#
I'm trying to make an arraylist but it is coming up with errors. The actors are already placed in the world but I want to sort them and change their attributes. What I've got so far:
1
2
3
4
5
6
List<Suspect> suspects = new ArrayList<Suspect>(); // works
suspects.add(suspect1); // doesn't work
suspects.add(suspect2); // doesn't work
suspects.add(suspect3); // doesn't work
suspects.add(suspect4); // doesn't work
Collections.shuffle(suspects); // works
What is it that I'm doing wrong here? Thanks!
danpost danpost

2017/4/11

#
How have you declared and assigned the variables 'suspect1', 'suspect2', 'suspect3' and 'suspect4'?
vermox vermox

2017/4/11

#
Yes, with
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void populate(){
 
        Player player = new Player();
        addObject(player, 9, 25);
 
        Suspect suspect1 = new Suspect();
        addToRandomEmptyCell(suspect1);
 
        Suspect suspect2 = new Suspect();
        addToRandomEmptyCell(suspect2);
 
        Suspect suspect3 = new Suspect();
        addToRandomEmptyCell(suspect3);
 
        Suspect suspect4 = new Suspect();
        addToRandomEmptyCell(suspect4);
    }
And these
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int getRandomNumber(int start,int end)
{
    int normal = Greenfoot.getRandomNumber(end-start+1);
    return normal+start;
}
 
private void addToRandomEmptyCell(Actor actor)
{
    int x = 0, y = 0;
    while (!getObjectsAt(x, y, null).isEmpty())
    {
        x = getRandomNumber(1, 24);
        y = getRandomNumber(1, 24);
    }
    addObject(actor, x, y);
}
danpost danpost

2017/4/11

#
You should probably build your array from within the populate method, as those references are lost as soon as the method is done executing. If you are not going to do anything with the shuffled array list immediately, then you need to move the first line of your first code post to outside the method.
You need to login to post a reply.