This site requires JavaScript, please enable it in your browser!
Greenfoot back
RårördaLingon
RårördaLingon wrote ...

2018/4/18

Adding Objects in the World with ArrayList?

RårördaLingon RårördaLingon

2018/4/18

#
Hi, noobie here. I am trying to place assorted mushrooms into the world. I added different numbers of each type of mushroom to the ArrayList to simulate probability. However, the code would only place the ten initiated objects into the world, regardless of the value of num.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void createM(int num)
    {
        ArrayList<Mushroom> mushrooms = new ArrayList<Mushroom>();
        for(int i = 0; i<4;i++)
            mushrooms.add(new Mushroom1());
        for(int i = 0; i<3;i++)
            mushrooms.add(new Mushroom2());
        for(int i = 0; i<2;i++)
            mushrooms.add(new Mushroom3());
        mushrooms.add(new Mushroom4());
        for(int i = 0; i < num; i++)
        {
            Mushroom m = mushrooms.get((int)(Math.random() * ((mushrooms.size() - 1) + 1)) + 0);
            addObject(m,(int)(Math.random() * ((getWidth() - 0) + 1) + 0), (int)(Math.random() * ((getHeight() - 0) + 1) + 0));
        }
    }
Thanks! (Just started using Greenfoot, thanks to all your help!)
danpost danpost

2018/4/18

#
You only create 10 mushrooms -- no more. You do not need an array list; you just need a random value and a switch block:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void createM(int num)
{
    for (int i=0; i<num; i++)
    {
        Actor actor = null;
        switch (Greenfoot.getRandomNumber(10))
        {
            case 0: case 1: case 2: case 3:  actor = new Mushroom1(); break;
            case 4: case 5: case 6:  actor = new Mushroom2(); break;
            case 7: case 8:  actor = new Mushroom3(); break;
            case 9:  actor = new Mushroom4(); break;
        }
        addObject(actor, Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
    }
}
It could also be done with if and if else statements inside the loop:
1
2
3
4
5
6
7
8
9
int rand = Greenfoot.getRandomNumber(10);
Actor actor = null;
if (rand < 4) actor = new Mushroom1();
else if (rand < 7) actor = new Mushroom2();
else if (rand < 9) actor = new Mushroom3();
else actor = new Mushroom4();
int x = Greenfoot.getRandomNumber(getWidth());
int y = Greenfoot.getRandomNumber(getHeight());
addObject(actor, x, y);
RårördaLingon RårördaLingon

2018/4/18

#
Thank you so much! It makes sense to me!
You need to login to post a reply.