Monday, October 12, 2009

HW4 example

// Vector.java
public class Vector {
 
private double dx,dy;
 
 
public Vector(double _x, double _y)
 
{
 
this.dx = _x;
 
this.dy = _y;
 
}
 
public void addVector(Vector otherVector)
 
{
 
this.dx += otherVector.dx;
 
this.dy += otherVector.dy;
 
}
 
public void subtractVector(Vector otherVector)
 
{
 
this.dx -= otherVector.dx;
 
this.dy -= otherVector.dy;
 
}
 
public void multiply(int a)
 
{
 
this.dx *= a;
 
this.dy *= a;
 
}
 
public double getMagnitude()
 
{
 
return Math.sqrt(dx*dx+dy*dy);
 
}
 
public void normalize()
 
{
 
double magnitude = getMagnitude();
 
if (magnitude==0)
   
return;
 
this.dx /= magnitude;
 
this.dy /= magnitude;
 
}
 
public String toString()
 
{
 
return ("("+Double.toString(this.dx)+", "+Double.toString(this.dy)+")");
 
}
 
}



//VectorDemo.java
public class VectorDemo {

 
public static void main(String[] args) {
 
// TODO Auto-generated method stub
 
Vector v1 = new Vector(3,4);
 
System.out.println(v1.toString());
  v1
.multiply(3);
 
System.out.println(v1.toString());
 
Vector v2 = new Vector(6, 8);
  v1
.subtractVector(v2);
 
System.out.println(v1.toString());
  v1
.normalize();
 
System.out.println(v1.toString());
 
}

}

No comments: