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

2015/8/21

Passing an array from world class to actor class

Evah Evah

2015/8/21

#
I have just started with greenfoot and m stuck coz i cant figure out how to use an array created in world class in my actor class pls help!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//code in world class
public void makeSnake()
    {
         
        for ( int i = 0; i < 6; i++)
        {
            snakeBody[i] = new Snake();
        }
        snakeBody[0].changeImageToHead();
        addObject(snakeBody[0],551,270);
        int currentX = snakeBody[0].getX();
        int currentY = snakeBody[0].getY();
        for ( int i = 1; i < 6; i++)
        {
            snakeBody[i].changeImageToTail();
            addObject(snakeBody[i],currentX - i*20,currentY);
        }
       // Snake.moveSnake(snakeBody);
         
        /*for(int i=1; i<6; i++)
        {
            snakeBody[i] = new Snake();
            addObject(snakeBody[i], 90+(snakeBody.length-i)*15, 30); // adding snake actor to the world
        }*/
    }
     
    public Snake getSnake()
    {
        for (int i=0; i < snakeBody.length ; i++ )
        {
            return snakeBody[i];
        }
    }
 
 
// code in snake class
public void snakeMove()
    {
       
      for (int i=0; i < snakeField.length ; i++ )
        {
            SnakeWorld w = (SnakeWorld) getWorld();
             
            snakeField[i] = w.getSnake();
        }
danpost danpost

2015/8/21

#
Your return statement within the for loop at line 29 will always return the first element of the 'snakeBody' array. You should be aware that a 'return' statement exits the method, terminating any loops and ignoring any following statements within that method. Therefore, your 'getSnake' method, as written, is equivalent to this:
1
2
3
4
public Snake getSnake()
{
    return snakeBody[0];
}
If you want to have the method return the entire array, then the return type must reflect that you are returning an array:
1
2
3
4
public Snake[] getSnake()
{
    return snakeBody;
}
If you want to have a specific one returned, you would need a method something like the following:
1
2
3
4
5
public Snake getSnake(int part)
{
    if (part < 0 || part >= snakeBody.length) return null;
    return snakeBody(part);
}
You need to login to post a reply.