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 CityTour { // This program computes the total distance of a city tour by Paulo, beginning // and ending at city A. He travels through an arbitrary number of cities // during his tour. public static void main (String[] args) { Point cityA = new Point(0, 0); // city A, where Paulo starts and ends Point cityLast = new Point(0, 0); // last city read Point cityNext = new Point(0, 0); // next city read float totalDistance = 0; // and total distance traveled so far. System.out.println("Enter the coordinates of city A: "); cityA.readPoint(); cityLast.movePoint(cityA); // start out with last city as city A System.out.println("Enter coordinates of next city, or ctrl-c: "); while (cityNext.readPoint()) { totalDistance = totalDistance + cityLast.distanceTo(cityNext); cityLast.movePoint(cityNext); System.out.println("Enter coordinates of next city, or ctrl-c: "); } totalDistance = totalDistance + cityLast.distanceTo(cityA); System.out.println("Total distance of Paulo's tour = " + totalDistance); System.out.print("starting and ending at "); cityA.displayPoint(); } }