public class Point { // This class defines the idea of a Point on an x-y graph. It can be used // in problems like Lab 3, where points represent locations of different // cities on the map. // Declarations -- these define the features of any object (variable) // in the class. For class Point, we need two integers to keep // track of the x-y coordinates of each point on the graph. private int xcoord, ycoord; // Constructor -- defines how any object declared for this class // will have its variables initialized. For class Point, the // two integer parameters identify the initial x-y coordinates // of a Point object public Point (int x, int y) { xcoord = x; ycoord = y; } // Methods -- define how any object in the class can be manipulated // (changed), combined with another object to compute a result, // pr displayed. The methods for class Point are: // dostamceTo(Point p) -- computes the distance from the // given point to another point p. The result // returned is a float. // movePoint(Point p) -- moves a Point from its // current x-y coordinates to those of Point p. // readPoint() -- reads two integers and assigns them to // the x and y coordinates of the given point. // Returns false if Keyboard.eof() occurs. // displayPoint() -- displays the x-y coordinates of the given // given point. public float distanceTo (Point p) { float d = (float)Math.sqrt(Math.pow(p.xcoord - xcoord, 2) + Math.pow(p.ycoord - ycoord, 2)); return d; } public void movePoint(Point p) { xcoord = p.xcoord; ycoord = p.ycoord; } public boolean readPoint() { System.out.print("x coordinate: "); xcoord = Keyboard.readInt(); if (!Keyboard.eof()) { System.out.print("y coordinate: "); ycoord = Keyboard.readInt(); return true; } else return false; } public void displayPoint() { System.out.print(" (" + xcoord + ", " + ycoord + ") "); } } public class Lab3Again { public static void main (String[] args) { Point cityA = new Point(0, 0); // city A, where Paulo works Point cityOther = new Point(0, 0); // any other city Point cityClosest = new Point(0, 0); // closest city so far float distanceClosest = 99; // and its distance to city A. System.out.println("Enter the coordinates of city A: "); cityA.readPoint(); System.out.println("Enter coordinates of next city, or ctrl-c: "); while (cityOther.readPoint()) { if (cityOther.distanceTo(cityA) < distanceClosest) { distanceClosest = cityOther.distanceTo(cityA); cityClosest.movePoint(cityOther); } System.out.println("Enter coordinates of next city, or ctrl-c: "); } System.out.println("Closest City is at distance " + distanceClosest); System.out.print("with coordinates"); cityClosest.displayPoint(); } }