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

2014/2/28

Using getObjectInRange()

blorange2 blorange2

2014/2/28

#
I have written this code to return all lamposts that are in range in the world.
    public boolean isLampPostInRange(){  
        return !getObjectsInRange(100, LampPosts.class).isEmpty();
    } 
However when a lamp post is in range I want to use one of its methods? So I want to say
    if(isLampPostInRange()){
        if(LampPosts.getCode() == 0){

    }
But I want to use that specific object that is within the range? Not lamposts generally?
danpost danpost

2014/2/28

#
Returning a boolean value from the 'isLampPostInRange' method will only inform the calling method whether there is one or not. What you want to do is have it return a LampPosts object:
public LampPosts getLampPostInRange(){
    if (getObjectsInRange(100, LampPosts.class).isEmpty()) return null;
    return (LampPosts)getObjectsInRange(100, LampPosts.class).get(0);
}
// or maybe this might be better as it only gets the list one time instead of twice
public LampPosts getLampPostInRange(){
    for (Object lamppost : getObjectsInRange(100, LampPosts.class)){
        return (LampPosts)lamppost;
    }
    return null;
}

// Now, your calling method can use this:
LampPosts lamppost = getLampPostInRange();
if (lamppost != null && lamppost.getCode() == 0){

}
blorange2 blorange2

2014/2/28

#
Thankyou very much DANPOST! .... I tweaked it slightly and it works perfectly
danpost danpost

2014/2/28

#
I did a little tweaking with editing it. You may want to take a look as to how I changed the second 'getLampPostInRange' code.
You need to login to post a reply.