We now redefine the class Particle to include a method to compute the distance between two particles. The application that follows creates two particles and gives their mutual separation. public class Particle
{
double x, y, mass;
public Particle(double x, double y)
{
this(x, y, 1.0);
}
public Particle(double x, double y, double mass)
{
this.x = x;
this.y = y;
this.mass = mass;
}
public double distanceFrom(Particle a)
{
double r2 = Math.pow(this.x - a.x, 2) + Math.pow(this.y - a.y,2);
return Math.sqrt(r2);
}
public double distanceFromOrigin()
{
return Math.sqrt(x*x + y*y);
}
}
public class MyApplication
{
public static void main(String[] args)
{
Particle a = new Particle(5.0, 7.0);
Particle b = new Particle(1.0, 2.0);
System.out.println("Distance of a from b = " + a.distanceFrom(b));
System.out.println("Distance of b from a = " + b.distanceFrom(a));
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment