ako man ni gi-copy from a book.. nya gi-review nako, murag wala man tingali sayop.. ni-compile man pud siya og tarong.
TryPackage.java [My Documents]
Code:
import Geometry.*;
public class TryPackage{
public static void main(String[] args){
double [][] coords = { {1.0,0.0}, {6.0,0.0},{6.0,10.0},{10,10},{10,-14},{8,-14}};
Point[] points = new Point[coords.length];
for(int i =0; i<coords.length;i++){
points[i] = new Point(coords[i][0],coords[i][1]);
}
Line[] lines = new Line[points.length -1];
double totalLength = 0;
for(int i = 0;i<points.length -1; i++){
lines[i] = new Line(points[i], points[i+1]);
totalLength += lines[i].length();
System.out.println("Line "+(i+1)+' '+lines[i] + " Lenght is " + lines[i].length());
}
System.out.println("\nTotal line length = "+totalLength);
}
}
Point.java [C:\Java\Packages\Geometry]
Code:
package Geometry;
public class Point {
public Point(double xVal, double yVal){
x = xVal;
y = yVal;
}
public Point(final Point oldPoint){
x = oldPoint.x;
y = oldPoint.y;
}
public void move(double xDelta, double yDelta){
x += xDelta;
y += yDelta;
}
public double distance(final Point aPoint){
return (Math.sqrt((x-aPoint.x)*(x-aPoint.x) + (y-aPoint.y)*(y-aPoint.y)));
}
public String toString(){
return Double.toString(x) + ", " + y;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public void setX(double inputX){
x = inputX;
}
public void setY(double inputY){
y = inputY;
}
private double x;
private double y;
}
Line.java
Code:
package Geometry;
public class Line{
public Line(final Point start, final Point end){
this.start = new Point(start);
this.end = new Point(end);
}
public Line(double xStart, double xEnd, double yStart, double yEnd){
start = new Point(xStart, yStart);
end = new Point(xEnd, yEnd);
}
public double length(){
return start.distance(end);
}
public String toString(){
return " (" + start+ "): ("+end+")";
}
public Point intersects(final Line line1){
Point localPoint = new Point(0,0);
double num = (this.end.getY() - this.start.getY())*(this.start.getX() - line1.start.getX()) -
(this.end.getX() - this.start.getX())* (this.start.getY() - line1.start.getY());
double denom = (this.end.getY() - this.start.getY())* (line1.end.getX() - line1.start.getX()) -
(this.end.getX() - this.start.getX())* (line1.end.getY() - line1.start.getY());
localPoint.setX(line1.start.getX() + (line1.end.getX() - line1.start.getX())*num/denom);
localPoint.setY(line1.start.getY() + (line1.end.getY() - line1.start.getY())*num/denom);
return localPoint;
}
Point start;
Point end;
}