控制台程序。
1 public class Point { 2 // Create a point from its coordinates 3 public Point(double xVal, double yVal) { 4 x = xVal; 5 y = yVal; 6 } 7 8 // Create a point from another point 9 public Point(Point point) { 10 x = point.x; 11 y = point.y; 12 } 13 14 // Convert a point to a string 15 @Override 16 public String toString() { 17 return x+","+y; 18 } 19 20 // Coordinates of the point 21 protected double x; 22 protected double y; 23 }
1 import java.util.LinkedList; 2 3 public class PolyLine { 4 // Construct a polyline from an array of points 5 public PolyLine(Point[] points) { 6 // Add the points 7 for(Point point : points) { 8 polyline.add(point); 9 } 10 } 11 // Construct a polyline from an array of coordinates 12 public PolyLine(double[][] coords) { 13 for(double[] xy : coords) { 14 addPoint(xy[0], xy[1]); 15 } 16 } 17 18 // Add a Point object to the list 19 public void addPoint(Point point) { 20 polyline.add(point); // Add the new point 21 } 22 23 // Add a point to the list 24 public void addPoint(double x, double y) { 25 polyline.add(new Point(x, y)); 26 } 27 28 // String representation of a polyline 29 @Override 30 public String toString() { 31 StringBuffer str = new StringBuffer("Polyline:"); 32 33 for(Point point : polyline) { 34 str.append(" "+ point); // Append the current point 35 } 36 return str.toString(); 37 } 38 39 private LinkedList<Point> polyline = new LinkedList<>(); 40 }
1 public class TryPolyLine { 2 public static void main(String[] args) { 3 // Create an array of coordinate pairs 4 double[][] coords = { {1, 1}, {1, 2}, { 2, 3}, 5 {-3, 5}, {-5, 1}, {0, 0} }; 6 7 // Create a polyline from the coordinates and display it 8 PolyLine polygon = new PolyLine(coords); 9 System.out.println(polygon); 10 // Add a point and display the polyline again 11 polygon.addPoint(10, 10); 12 System.out.println(polygon); 13 14 // Create Point objects from the coordinate array 15 Point[] points = new Point[coords.length]; 16 for(int i = 0; i < points.length; ++i) 17 points[i] = new Point(coords[i][0],coords[i][1]); 18 19 // Use the points to create a new polyline and display it 20 PolyLine newPoly = new PolyLine(points); 21 System.out.println(newPoly); 22 } 23 }