JAVA學習之類與物件例題分享(兩點確定直線並進行相關操作)
阿新 • • 發佈:2018-12-15
最近在自學JAVA,學到類與物件章節,分享一個自我感覺還可以的例題答案,自己編寫的,發出來希望大神們知道一二。
源程式如下:
package Line_Test; public class Line_Test { public static void main(String[] args) { // TODO Auto-generated method stub // 線段測試 Line line = new Line(new Line.Point(2,3),new Line.Point(4,5)); line.Print_Point(); line.Print(); System.out.println(); Line line1 = new Line(new Line.Point(2,3),new Line.Point(2,5)); line1.Print_Point(); line1.Print(); System.out.println(); Line line2 = new Line(new Line.Point(2,3),new Line.Point(4,3)); line2.Print_Point(); line2.Print(); System.out.println(); } } //線段類 class Line{ public static class Point{ private float x,y; public Point() { x = 2; y = 3; } public Point(float x,float y) { this.x = x; this.y = y; } } private Point p0; private Point p1; // 過載構成函式 public Line() { this.p0 = new Point(2,3); this.p1 = new Point(4,5); } // 過載構成函式 public Line(Point p0,Point p1) { this.p0 = new Point(p0.x,p0.y); this.p1 = new Point(p1.x,p1.y); } // 線段長度 public float Line_Length() { if(this.isLineH()) { return Math.abs(p1.y-p0.y); } else if(this.isLineV()) { return Math.abs(p1.x-p0.x); } else { return (float)Math.sqrt((Math.pow((p1.x-p0.x),(p1.x-p0.x))+Math.pow((p1.y-p0.y),(p1.y-p0.y)))); } } // 線段水平 true:Yes false:No public boolean isLineH() { return (p0.x==p1.x); } // 線段垂直 true:Yes false:No public boolean isLineV() { return (p0.y==p1.y); } // 線段斜率 public float LineSlope() { return (p1.y-p0.y)/(p1.x-p0.x); } // 求線段中點 public Point LineMid() { Point p = new Point(); p.x = (p1.x+p0.x)/2.0f; p.y = (p1.y+p0.y)/2.0f; return p; } // 列印當前點 public void Print_Point() { System.out.print("Point0:("+p0.x+","+p0.y+")"+" "); System.out.print("Point1:("+p1.x+","+p1.y+")"+"\r\n"); } // 列印計算結果 public void Print() { System.out.println("Line length:"+this.Line_Length()); System.out.println("Line horizontal?"+this.isLineH()); System.out.println("Line vertical?"+this.isLineV()); System.out.println("Line slope:"+this.LineSlope()); System.out.println("Line mid:("+this.LineMid().x+","+this.LineMid().y+")"); } }
執行結果如下:
感覺JAVA用起來是比較方便,第一次寫JAVA程式,還望大神指導一下不足之處。