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

2012/4/3

Moment of great amnesia

darkmist255 darkmist255

2012/4/3

#
Well, I know I've used this before in my code (I'm sure of it) but I read through many of my class files and haven't found it yet. When I use this code
    public void getDistanceBetween(object object1, object object2)
    {
        double distance = Math.sqrt(Math.abs((object2.getY()-object1.getY())*(object2.getY()-object1.getY()) + ((object2.getX()-object1.getX())*(object2.getX()-object1.getX()))));
        return distance;
    }
It says "cannot find symbol - class object" I know that it wants me to specify what type of variable it is, my question is what is the "universal" symbol I can put there that won't care what actor class it contains?
danpost danpost

2012/4/3

#
Java is case sensitive, try: getDistanceBetween(Object object1, Object object2)
darkmist255 darkmist255

2012/4/3

#
Curse you case sensitivity! Well at least I don't have early onset Alzheimer's :D.
darkmist255 darkmist255

2012/4/3

#
Yup thanks :D! That was recognized.
nccb nccb

2012/4/3

#
darkmist255: you probably mean Actor, not Object. Unless you've made your own class called Object, which is usually a bad idea. Interestingly, you don't need the Math.abs call. You're squaring the distance between the two y coordinates: a square must always be positive or zero, because multiplying two positives is positive, multiplying two negatives is positive, and multiplying two zeroes is zero. Similarly, the square of the x distance is also positive or zero. When you add together two numbers that are zero or higher, you must get a result that is zero or higher. Hence, no need for the abs call. Additionally, if you want to use it, Java has a Math.hypot call that shortens the code for this kind of thing. The body of your method could be changed to:
public void getDistanceBetween(Actor object1, Actor object2)  
{  
    return Math.hypot(object2.getY()-object1.getY(), object2.getX()-object1.getX());
}
The hypot call works out the hypotenuse given the other two sides of the triangle, which is what your code was also doing.
darkmist255 darkmist255

2012/4/4

#
Math.hypot(x, y), thanks for sharing that! Yeah the abs() is redundant now that you mention it. And yeah I changed it to Actor instead of Object once I realized I need to call some methods within them. Thanks :D!
You need to login to post a reply.