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

2020/3/26

creating an array of objects?

LewisEro LewisEro

2020/3/26

#
i get the syntax error:
']' expected
line 13,14,15 ive looked up how to properly declare creating object arrays, but according to what ive read now this should be the correct syntax..
public class MyWorld extends World
{
    PC player = new PC();
    private int nOfSkulls = 3;
    FloatingSkull skull[] = new FloatingSkull(player)[nOfSkulls];
    skull[0] = new FloatingSkull();
    skull[1] = new FloatingSkull();
    skull[2] = new FloatingSkull();
    EnvObj building = new EnvObj();
    boolean roomSwitcher;

    public MyWorld()
    {    
        super(600, 600, 1); 
        //setPaintOrder(Shadowball.class,Smoke.class);
        setPaintOrder(FloatingSkull.class, SkullBeam.class, Shadowball.class,Smoke.class);
        addObject(player, 300, 200);   
        addObject(skull1, 20, 20);
        addObject(skull1, 400, 400);
        addObject(skull2, 500, 500);

    }
LewisEro LewisEro

2020/3/26

#
creating them in this manner works fine :
public class MyWorld extends World
{
    PC player = new PC();
    FloatingSkull skull = new FloatingSkull(player);
    FloatingSkull skull1 = new FloatingSkull(player);
    FloatingSkull skull2 = new FloatingSkull(player);
    EnvObj building = new EnvObj();
    boolean roomSwitcher;

    /**
     * Constructor for objects of class MyWorld.
     * 
     */
    public MyWorld()
    {    
        super(600, 600, 1); 
        //setPaintOrder(Shadowball.class,Smoke.class);
        setPaintOrder(FloatingSkull.class, SkullBeam.class, Shadowball.class,Smoke.class);
        addObject(player, 300, 200);   
        addObject(skull, 20, 20);
        addObject(skull1, 400, 400);
        addObject(skull2, 500, 500);

    }
but i'd like to learn about object arrays, so this approach does not satisfy me..
danpost danpost

2020/3/26

#
When you create an array (attempted at line 5), the type (after new) does not get any parameters. In fact, it does not receive round parenthesis after it at all. You are not creating any FloatingSkull objects when you create the array, so nothing is being passed. The argument goes with the code that actually creates the FloatingSkull objects (lines 6 thru 8)..
danpost danpost

2020/3/26

#
Second thing is that lines 6 thru 8 are not declaration lines (they are assignment lines) and cannot be placed outside a method. In your first code block above, you can replace lines 4 thru 8 with the following:
FloatingSkull[] skull =
{
    new FloatingSkull(player),
    new FloatingSkull(player),
    new FloatingSkull(player)
};
This declares and creates the array and assigns the elements, setting its size, all in one statement.
LewisEro LewisEro

2020/3/26

#
thank you!
You need to login to post a reply.