Point.java


Below is the syntax highlighted version of Point.java from §3.3 Modular Programming.

/*************************************************************************
 *  Compilation:  javac Point.java
 *  Execution:    java Point
 *
 *  Implementation of 2D point using rectangular coordinates.
 *
 *************************************************************************/

public class Point { 
   private double x;
   private double y; 
   
   // create and initialize a random point in unit square
   public Point() {
      this.x = Math.random();
      this.y = Math.random();
   }

   // create and initialize a point with given (x, y)
   public Point(double x, double y) {
      this.x = x;
      this.y = y;
   }
  
   // accessor methods
   public double x() { return x; }
   public double y() { return y; }

   // return Euclidean distance between p and q
   public double distanceTo(Point q) {
      Point p = this;
      if (q == null) return Double.MAX_VALUE;
      double dx = p.x - q.x;
      double dy = p.y - q.y;
      return Math.sqrt(dx*dx + dy*dy);
   }

   // return Euclidean distance between this and p
   public void draw(Draw d) {
      StdDraw.go(x, y);
      StdDraw.spot(5);
   }

   // return Euclidean distance between this and p
   public void drawTo(Point q) {
      Point p = this;
      StdDraw.penUp();
      StdDraw.go(p.x, p.y);
      StdDraw.penDown();
      StdDraw.go(q.x, q.y);
      StdDraw.penUp();
   }

   // return string representation of this point
   public String toString() { return "(" + x + ", " + y + ")"; } 


   // test client
   public static void main(String[] args) {
      Point p = new Point();
      System.out.println("p  = " + p);
      Point q = new Point(0.5, 0.5);
      System.out.println("q  = " + q);
      System.out.println("dist(p, q) = " + p.distanceTo(q) + " = " + q.distanceTo(p));
   }
}


Last updated: Sat Jan 15 12:24:16 EST 2005 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.