자바

점3개로 삼각형 넓이 구하기 예제

chantleman 2024. 7. 15. 12:26

point 클래스

public class Point {
	int x;
	int y;
	
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

 

 

triagle 클래스

public class Triangle {

	Point p1;
	Point p2;
	Point p3;
	double area;
	
	public Triangle(Point p1, Point p2, Point p3) {
		this.p1=p1;
		this.p2=p2;
		this.p3=p3;
		
		area = Math.abs(((p1.x*p2.y + p2.x*p3.y + p3.x*p1.y)
				- (p1.x*p3.y + p2.x*p1.y + p3.x*p2.y)))/2.0;
	}
	
	public Triangle(int x1, int y1, int x2, int y2, int x3, int y3) {
//		p1= new Point(x1, y1);
//		p2= new Point(x2, y2);
//		p3= new Point(x3, y3);
		
		
		//위 생성자 재호출해서 area 구하기
		this(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3));
		
	}
	
	
	public static void main(String[] args) {
		Triangle t1 = new Triangle(0,0, 10,0, 0,10);
		System.out.println(t1.area);
		
		Triangle t2 = new Triangle(new Point(0,0), new Point(10,0), new Point(0,10));
		System.out.println(t2.area);
	}
	
}

 


toString() 이용하기

 

point 클래스

public class Point {
	int x;
	int y;
	
	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	
	
	@Override
	public String toString() {
		return "("+x+", "+y+")";
	}

 

 

Triangle 클래스

public class Triangle {

	Point p1;
	Point p2;
	Point p3;
	double area;
	
	public Triangle(Point p1, Point p2, Point p3) {
		this.p1=p1;
		this.p2=p2;
		this.p3=p3;
		
		area = Math.abs(((p1.x*p2.y + p2.x*p3.y + p3.x*p1.y)
				- (p1.x*p3.y + p2.x*p1.y + p3.x*p2.y)))/2.0;
	}
	
	public Triangle(int x1, int y1, int x2, int y2, int x3, int y3) {
		this(new Point(x1, y1), new Point(x2, y2), new Point(x3, y3));		
	}
	
	
	
	
	@Override
	public String toString() {
		return "넓이: "+area +"\n" + p1 +", "+p2+", "+ p3;
	}
	
	

	public static void main(String[] args) {
		Triangle t1 = new Triangle(0,0, 10,0, 0,10);
		System.out.println(t1);
		
		
		Triangle t2 = new Triangle(new Point(0,0), new Point(10,0), new Point(0,10));
		System.out.println(t2);
		
		
	}
	
}

'자바' 카테고리의 다른 글

enum  (0) 2024.07.17
생산자, 오버로딩 활용하여 원기둥 부피 구하기 예제  (0) 2024.07.15
constructor, 생성자  (0) 2024.07.15
버블 소팅  (0) 2024.07.12
버블 소팅 이용한 로또 예제  (0) 2024.07.12