Java 上機測驗2020.4.17

4月17日上機課 堂上作業:
1、編寫一個Point類,要求如下:
屬性:橫座標、縱座標(double類型)
方法:
(1) 無參數的構造方法:調用1個參數的構造方法,橫、縱座標都設置爲0
(2) 包含1個參數的構造方法:調用2個參數的構造方法,橫、縱座標都設置爲參數值
(3) 包含2個參數的構造方法:分別把參數的值賦值給橫、縱座標。
(4) double distance(); 求該點到原點的距離。
(可用double b=Math.sqrt( a );求某數的平方根 )
(5) double distance(double a, double b); 求該點到座標爲(a,b )的點的距離
(6) double distance(Point p);求該點到另一點p的距離。
(7) void print(); 輸出該點的座標。

代碼

package game;

public class Person {

	public static void main(String[] args) {
		Point text1 = new Point();
		Point text2 = new Point(3);
		Point text3 = new Point(3, 4);
		
		text1.print();
		System.out.println(text2.distance());
		System.out.println(text3.distance(text2));
		System.out.println(text2.distance(12, 6));
	}
}
class Point{
	private double x,y;
	
	public Point() { this(0); }

	public Point(double x) { this(x, x); }

	public Point(double x, double y) {
		super();
		this.x = x;
		this.y = y;
	}
	public double distance() { return Math.sqrt(Math.pow(Math.abs(this.x), 2)+Math.pow(Math.abs(this.x), 2)); }
	public double distance(double a, double b) { return Math.sqrt(Math.pow(Math.abs(this.x-a), 2)+Math.pow(Math.abs(this.x-b), 2));  }
	public double distance(Point p) { return this.distance(p.x, p.y); }
	public void print() { System.out.println(this.x+" "+this.y); }	
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章