Java設計一個類代表二維空間的一個點,設計一個類代表二維空間的一個圓,計算面積,,並寫程序驗證計算一個點(Point對象)是否在圓(Cricle對象)內

題目要求:

(1) 設計一個類代表二維空間的一個點
(2) 設計一個類代表二維空間的一個圓。要求兩個成員變量。一個是圓心,一 個是半徑,提供計算面積的方法。
(3) 爲上述Cricle類添加一個方法,計算一個點(Point對象)是否在圓(Cricle對象)內,並寫程序驗證

public class Main {
		public static void main(String[] args) {
			Cricle1 c = new Cricle1(0, 0, 3) ; //傳入圓心與半徑
			//求面積 
			System.out.println("圓的面積爲:"+c.size());
			//判斷一點是否在圓內
			if(c.isIn(2, 2))
				System.out.println("在圓內");
			else
				System.out.println("不在圓內");
		}
}
class Cricle1{
		double x1 , y1 , r ; //分別代表圓心的兩座標與圓的半徑

		public Cricle1(double x1, double y1, double r) {
			super();
			this.x1 = x1;
			this.y1 = y1;
			this.r = r;
		}
		
		public double size () {//求面積,傳半徑作爲參數
			return Math.PI*r*r;
		}
		
		public boolean isIn (double x2 , double y2) {//判斷點是否在圓內,傳入隨便一點的座標
			if( Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2) >= Math.pow(r, 2))
				return false ;
			else
				return true ; 
		}
}

在這裏插入圖片描述
對於上面的代碼,你是否感覺到一絲錯意呢?
沒錯,上面的代碼沒有按照題目中給出的要求定義一個Point的類來做

而之所以將上面的代碼擺上去,是因爲除了沒有定義Point類外,運算步驟都是正確的沒有任何問題的,可以將上面的代碼作爲一種解題思路,在以後能夠更好的變通
下面給出正確的代碼:

public class Text_1_1 {
			public static void main(String[] args) {
				Point p1 = new Point(0, 0);
				Point p2 = new Point(2, 0);
				Cricle c = new Cricle() ;
				c.setP1(p1);//圓心
				c.setP2(p2);//隨便一點
				c.setR(2);//半徑
				c.sum();//面積
				c.inOrOut();//是否在圓內
			}
}
class Point{
		private double x,y;//點的座標

		public Point(double x, double y) {
			super();
			this.x = x;
			this.y = y;
		}

		public double getX() {
			return x;
		}

		public void setX(double x) {
			this.x = x;
		}

		public double getY() {
			return y;
		}

		public void setY(double y) {
			this.y = y;
		}
		
}
class Cricle {
		Point p1 ; // 圓心
		Point p2 ; // 隨便一點
		private double r ;//半徑
		
		public void sum () {//求圓面積
			System.out.println("圓的面積爲:"+Math.PI*r*r);
		}
		
		public void inOrOut () {//判斷一點是否在圓內
			if( Math.pow( p1.getX()-p2.getX() , 2) + Math.pow(  p1.getY()-p2.getY() , 2 ) >= Math.pow(r, 2)) 
				System.out.println("不在圓內");
			else
				System.out.println("在圓內");
		}

		public Point getP1() {
			return p1;
		}

		public void setP1(Point p1) {
			this.p1 = p1;
		}

		public Point getP2() {
			return p2;
		}

		public void setP2(Point p2) {
			this.p2 = p2;
		}

		public double getR() {
			return r;
		}

		public void setR(double r) {
			this.r = r;
		}
		
}

在這裏插入圖片描述
是不是今天有漲知識了呢?
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章