// Programmer: Sriram Pemmaraju. 2/18/07 import java.util.*; // A class to represent points in the Euclidean plane public class Point implements Comparable{ public double x; public double y; public Point (double newX, double newY) { x = newX; y = newY; } // A constructor that constructs a randomly generated // point both of whose coordinates are the range 0 through d, // where d is a given integer parameter. Since each coordinate // is generated uniformly at random in the range 0 through d, // the result is a point that is dropped uniformly at random // in a d by d square public Point (int d) { // Random is a class in java.util Random rand = new Random(); //nextDouble(), a method in the Random class //returns a random double in the range 0 through 1 x = d*rand.nextFloat(); y = d*rand.nextFloat(); } public void displayPoint() { System.out.println("x = " + x + " y = " + y); } // toString() is a commonly implemented method in any class // and is meant to return a string that "textually represents" // this object. toString() is defined in the Object class and // all classes inherit this method. Thus one could use the toString() // method on a Point object even without explicitly defining it, // as below. You might want to experiment with getting rid of // the toString() given below and then calling the toString() // method on a Point object to see how the default toString() // behaves. public String toString() { return "x = " + x + " y = " + y; } // Imposes a lexicographic total ordering on points. In other words, // given Points p_1 and p_2, whichever point p_1 has smaller // x-coordinate is considered the smaller point; if the x-coordinates // are the same, then whichever point has smaller y-coodinate is the // smaller. If both x and y coordinates are identical, then the points // are considered equal. public int compareTo(Point newP) { if(x < newP.x) return -1; else if ((x == newP.x) && (y < newP.y)) return -1; else if ((x == newP.x) && (y == newP.y)) return 0; else return 1; } public boolean equals(Point newP) { return (this.compareTo(newP) == 0); } // Computes the Euclidean distance between this Point and the // given Point newP public double distance(Point newP) { // sqrt is a static method defined in the java.lang.Math class // It returns a double. return Math.sqrt((x - newP.x)*(x - newP.x) + (y - newP.y)*(y - newP.y)); } }