Java学习——小题练习

Write a program that prompts the user to entern three points (x1,y1),(x2,y2), (x3,y3) of a triangle and displays its area. The formula for computing the area of a triangle is s = (side1 + side2 + side3)/2; area = Math.sqrt(s (s - side1) (s - side2) (s - side3));

input style :
Enter three points for a triangle,there is a space among the values. i.e : 1.5 -3.4 4.6 5 9.5 -3.4

output style:
Output the area. Keep the two decimal places. i.e : The area of the triangle is 33.60.

input sample:
1.5 -3.4 4.6 5 9.5 -3.4
output sample:
The area of the triangle is 33.60.

public class AreaOfTriangle
{
	private double x1;
	private double y1;
	private double x2;
	private double y2;
	private double x3;
	private double y3;
	
	AreaOfTriangle(double x1,double y1,double x2,double y2,double x3,double y3){
		this.x1 = x1; this.y1 = y1;
		this.x2 = x2; this.y2 = y2;
		this.x3 = x3; this.y3 = y3;	
	}
	
	private double getSide1() {
		return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 -y2));
	}
	private double getSide2() {
		return Math.sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 -y3));
	}
	private double getSide3() {
		return Math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 -y3));
	}
	private double getS() { 
		return (getSide1() + getSide2() + getSide3()) / 2;	
	}
	
	public double calculateArea() {
		return Math.sqrt(getS() * (getS() - getSide1()) *
				(getS() - getSide2()) * (getS() - getSide3()));
		
	}

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		double x1 = sc.nextDouble();
		double y1 = sc.nextDouble();
		double x2 = sc.nextDouble();
		double y2 = sc.nextDouble();
		double x3 = sc.nextDouble();
		double y3 = sc.nextDouble();
		AreaOfTriangle triangle = new AreaOfTriangle(x1,y1,x2,y2,x3,y3);
		System.out.printf("%.2f\n",triangle.calculateArea());
		
		sc.close();
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_43574957/article/details/85042105