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

2016/11/28

For loop creating random walls

MJBelmer MJBelmer

2016/11/28

#
I'm writing a for loop in my prepare method of my world to put in 1 - 5 wall objects randomly but not within 50 pixels of the world's edge. My code is giving an error and I'm unsure as to why as everything (to me) looks right.
        int i;
        for ( i = 0; i < Greenfoot.getRandomNumber(4) + 1; i++)
        {
            Wall wall[i] = new Wall();
            addObject(wall[i], Greenfoot.getRandomNumber(660) + 50, Greenfoot.getRandomNumber(660) + 50);
        }
MJBelmer MJBelmer

2016/11/28

#
it's giving me an error where the wall is.
Super_Hippo Super_Hippo

2016/11/28

#
You could simply remove the array. And including line 1 into line 2 and line 4 into line 5, it will be this:
for (int i = 0; i < Greenfoot.getRandomNumber(4) + 1; i++)
{
    addObject(new Wall(), Greenfoot.getRandomNumber(660) + 50, Greenfoot.getRandomNumber(660) + 50);
}
danpost danpost

2016/11/28

#
To explain the error, your line 4 it totally messed up. I cannot say whether it is trying to declare a Wall object reference field or an array that holds references to Wall objects. I think that what is on the left of the equal sign is incorrect for either declaration. The ways to declare an array legally are:
// with 'i' assigned as
int i = 1+Greenfoot.getRandomNumber(5); // range 1 to 5

Wall[] wall = new Wall[i];
// or
Wall wall[] = new Wall[i];
Then, you would assign Wall object to be its elements:
for (int i=0; i<wall.length; i++)
{
    wall[i] = new Wall();
}
You could also set the elements while declaring the size like this (if the number of elements is not variable):
Wall wall[] = // or 'Wall[] wall ='
{
    new Wall(),
    new Wall(),
    new Wall(),
    new Wall(),
    new Wall()
};
You need to login to post a reply.