Download source code and powerpoint from oop2.zip
C:\ece538>java Vec2 A = (3.0 4.0) B = (2.0 -1.0) sum = A+B = (5.0 3.0) sum - B = (3.0 4.0) magnitude(A) is 5.0 Angle from B to A: 79.6952 |
Vec2.java
// Vec2 version 3, static methods public class Vec2 { private String name; private double kx, ky; public Vec2(String name, double kx, double ky) { this.name = name; this.kx = kx; this.ky = ky; } public Vec2(double kx, double ky) { this.kx = kx; this.ky = ky; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setVec(double kx, double ky) { this.kx = kx; this.ky = ky; } public double getX() { return kx; } public double getY() { return ky; } public String toString() { String s = "(" + kx + " " + ky + ")"; if (name==null) return s; return name + " = " +s; } static public Vec2 sum(Vec2 a, Vec2 b) { return new Vec2(a.kx+b.kx,a.ky+b.ky); } static public Vec2 diff(Vec2 a, Vec2 b) { return new Vec2(a.kx-b.kx,a.ky-b.ky); } // returns magnitude of 2D vector public double magn() { return Math.sqrt(kx*kx+ky*ky); } final static double radg = Math.atan(1.0)/45.0; // returns dot product static public double dot(Vec2 a, Vec2 b) { return (a.kx*b.kx+a.ky*b.ky); } // returns cross product static public double cross(Vec2 a, Vec2 b) { return (a.kx*b.ky-a.ky*b.kx); } // returns angle (in degrees) between two vectors static public double angle(Vec2 a, Vec2 b) { double c, s; c = dot(a,b); s = cross(a,b); return Math.atan2(s,c)/radg; } static public void main(String[] args) { Vec2 A = new Vec2("A",3.0,4.0); Vec2 B = new Vec2("B",2.0,-1.0); Vec2 sum = Vec2.sum(A,B); System.out.println(A+"\n"+B+"\nsum = A+B = "+sum); Vec2 diff = Vec2.diff(sum,B); System.out.println("sum - B = " + diff); System.out.println("magnitude(A) is "+A.magn()); System.out.format("Angle from B to A: %g%n" , Vec2.angle(B,A)); } }
Maintained by John Loomis, updated Sat Jan 18 12:37:29 2020