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

2013/10/19

Adding objects with arrays?

Aermus Aermus

2013/10/19

#
Hello, I'm trying to add multiple objects at once with arrays. I currently have 3 arrays, 1 for the images, and separate arrays for the coordinates. The Following code obviously doesn't work because the addObject(obstakel, xCoords, yCoords); is wrong. What is the proper way of doing this? Thanks in advance!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Stad extends World
{   
    private String[] img =
    { "Gebouw1.jpg", "Gebouw2.jpg", "Gebouw3.jpg", "Gebouw4.jpg", "Gebouw5.jpg", "Gebouw6.jpg", "Gebouw7.jpg", "Gebouw8.jpg", "Gebouw9.jpg", "Gebouw10.jpg", "Gebouw11.jpg", "Gebouw12.jpg", "Gebouw13.jpg", "Gebouw14.jpg", "Gebouw15.jpg", "Gebouw16.jpg", "Gebouw17.jpg", "Gebouw18.jpg", "Gebouw19.jpg", "Gebouw20.jpg", "Gebouw21.jpg", "Gebouw22.jpg", "Gebouw23.jpg" };
      
    private String[] xCoords =
    { "799", "20", "1419", "1038", "503", "1556", "1353", "1336", "1354", "514", "661", "713", "767", "861", "240", "1354", "462", "711", "1114", "124", "367", "272", "1249" };
     
    private String[] yCoords =
    { "37", "383", "166", "352", "279", "566", "324", "370", "418", "455", "424", "825", "424", "455", "506", "598", "556", "597", "649", "784", "784", "800", "814" };
     
    public Stad(){      
        super(1600, 875, 1);
        PlaatsObstakels();       
    }
     
    public void PlaatsObstakels(){
        for(int i = 0; i < img.length; i++) {
            Obstakel obstakel = new Obstakel();
            addObject(obstakel, xCoords[i], yCoords[i]);
        }
    }   
}
Aermus
danpost danpost

2013/10/19

#
The problem is you are trying to supply String objects as coordinates to place the objects. Remove all quotes from around your numbers in the arrays and change the type of those number arrays from 'String' to 'int'.
Aermus Aermus

2013/10/19

#
danpost wrote...
The problem is you are trying to supply String objects as coordinates to place the objects. Remove all quotes from around your numbers in the arrays and change the type of those number arrays from 'String' to 'int'.
Doh! stupid me.. hehe thanks, it works ;) Now i need to find a way to implement the pictures along with the objects. Ill let you know when i figured it out. I think i can use Chapter 5 with the Piano scenario for that.
danpost danpost

2013/10/19

#
You should be able to use 'obstakel.setImage(img);' either before or after adding it into the world.
Aermus Aermus

2013/10/19

#
danpost wrote...
You should be able to use 'obstakel.setImage(img);' either before or after adding it into the world.
Thanks again, it works perfectly.
You need to login to post a reply.