Advertisement
ppathak35

vectors in java

Jun 8th, 2022
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. class Vector{
  2.     int x;
  3.     int y;
  4.     int z;
  5.    
  6.     Vector(int x, int y, int z) {
  7.         this.x = x;
  8.         this.y = y;
  9.         this.z = z;
  10.     }
  11.    
  12.     @Override public String toString() {
  13.         return "Vector(" + x + "," + y + "," + z + ")";
  14.     }
  15.    
  16.     Vector add(Vector v) {
  17.         int newx = this.x + v.x;
  18.         int newy = this.y + v.y;
  19.         int newz = this.z + v.z;
  20.         Vector vector = new Vector(newx, newy, newz);
  21.         return vector;
  22.     }
  23.    
  24.     Vector sub(Vector v) {
  25.         int newx = this.x - v.x;
  26.         int newy = this.y - v.y;
  27.         int newz = this.z - v.z;
  28.         Vector vector = new Vector(newx, newy, newz);
  29.         return vector;
  30.     }
  31.    
  32.     Vector mul(int c) {
  33.         // Method overloading
  34.         int newx = this.x * c;
  35.         int newy = this.y * c;
  36.         int newz = this.z * c;
  37.         Vector vector = new Vector(newx, newy, newz);
  38.         return vector;
  39.     }
  40.    
  41.     int mul(Vector v) {
  42.         // Method overloading ( dot product)
  43.         return this.x * v.x + this.y * v.y + this.z * v.z;
  44.     }
  45.    
  46.     double magnitude() {
  47.         // this holds current instance
  48.         return Math.sqrt(this.mul(this));
  49.     }
  50. }
  51.  
  52. class VectorOps {
  53.     public static void main(String args[]) {
  54.         Vector v1 = new Vector(3, 5, 2);
  55.         Vector v2 = new Vector(4, 4, 1);
  56.         System.out.println(v1);
  57.         System.out.println(v2);
  58.         System.out.println(v1.add(v2));
  59.         System.out.println(v1.sub(v2));
  60.         System.out.println(v1.mul(3));
  61.         System.out.println(v1.mul(v2));
  62.         System.out.println(v1.magnitude());
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement