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

2014/1/26

use a String in isTouching()??

Nooyi Nooyi

2014/1/26

#
Hello, I need some help with this code (the world is 8 x 8):
public int numberOfActors(String actor)   {
        int beginX = getX();
        int beginY = getY();
        int numberActor = 0;
        for(int x = 0; x < 8; x++)  {
            for(int y = 0; y < 8; y++)  {
                setLocation(x,y);
                if(isTouching( ??? .class)) {
                    numberActor++;
                }
            }
        }
        setLocation (beginX,beginY);
        return anzahlActor;
    }
I don't know how to write that greenfoot should integrate the name in the string actor. Is there someone who could help me? :)
danpost danpost

2014/1/26

#
There is something amiss about this. Give me a second. Why cannot you use:
int anzahlActor = getWorld().getObjects(ClassName.class).size();
By replacing 'ClassName' with the name of the class, this should give you the count of objects of that class that are in the world.
davmac davmac

2014/1/26

#
You can use:
Class.forName(name)
To dynamically find a class using its name. I think this is what you want? i.e.
                if(isTouching(Class.forName(actor))) {  
However, it's probably much better just to pass a Class into your method rather than a String:
    public int numberOfActors(Class actor)   {  
            int beginX = getX();  
            int beginY = getY();  
            int numberActor = 0;  
            for(int x = 0; x < 8; x++)  {  
                for(int y = 0; y < 8; y++)  {  
                    setLocation(x,y);  
                    if(isTouching(actor)) {  
                        numberActor++;  
                    }  
                }  
            }  
            setLocation (beginX,beginY);  
            return anzahlActor;  
        }  
You need to login to post a reply.