java实现给三个点求面积_Java给出3个点,做三角形判断

问题:
给定平面上任意三个点的坐标(x1,y1)、(x2,y2)、(x3,y3),检验它们能否构成三角形。
输入格式:
输入在一行中顺序给出6个[-100, 100]范围内的数字,即3个点的坐标x1, y1, x2, y2, x3, y3。
输出格式:
若这3个点不能构成三角形,则在一行中输出“Impossible”;若可以,则在一行中输出该三角形的周长和面积,格式为“L = 周长, A = 面积”,输出到小数点后2位。
输入样例1:
4 5 6 9 7 8
输出样例1:
L = 10.13, A = 3.00
输入样例2:
4 6 8 12 12 18
输出样例2:
Impossible 求解代码:
import java.text.DecimalFormat;
import java.util.Scanner;
//点
class Point{
//x坐标
private double x;
//y坐标
private double y;
public Point(double x, double y)
{
this.x=x;
this.y=y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
【java实现给三个点求面积_Java给出3个点,做三角形判断】public void setY(double y) {
this.y = y;
}
}
//直线
class Line
{
private Point point1;
private Point point2;
//斜率
private double slope;
private double length;
public Line(Point point1 , Point point2)
{
this.point1=point1;
this.point2=point2;
this.slope=(point1.getY()-point2.getY())/(point1.getX()-point2.getX());
this.length=Math.sqrt( Math.pow(Math.abs(point1.getY()-point2.getY()), 2)+Math.pow(Math.abs(point1.getX()-point2.getX()), 2));
}
public double getSlope() {
return slope;
}
public boolean isParallel(Line line)
{
if(this.slope==line.getSlope())
return true;
return false;
}
public double getLength() {
return length;
}
}
/*给定平面上任意三个点的坐标(x1,y1)、(x2,y2)、(x3,y3),检验它们能否构成三角形。
*1. 不存在平行的两条直线
*2. 两边之和大于第三边
3. 两边直插小雨第三边
* */
public class Main {
public static void main(String[] args) {
//控制台输入
Scanner scanner = new Scanner(System.in);
double x1,x2,x3,y1,y2,y3;
//从控制台获得3个坐标点(x1,y1),(x2,y2),(x3,y3)
x1=scanner.nextDouble();
y1=scanner.nextDouble();
x2=scanner.nextDouble();
y2=scanner.nextDouble();
x3=scanner.nextDouble();
y3=scanner.nextDouble();
//构造成3个Point对象
Point point1 = new Point(x1,y1);
Point point2 = new Point(x2,y2);
Point point3 = new Point(x3,y3);
//得到3条直线
Line line1 = new Line(point1,point2);
Line line2 = new Line(point1,point3);
Line line3 = new Line(point2,point3);
//存储三条直线的长度
double len1 = line1.getLength();
double len2 = line2.getLength();
double len3 = line3.getLength();
//判断三条直线是存在平行
if( line1.isParallel(line2) || line1.isParallel(line3) || line2.isParallel(line3))
{
System.out.println("Impossible");
}
//判断不平行的三条直线是否能构成三角形
else if( (len1+len2)len3 || Math.abs(len1-len3)>len2 || Math.abs(len2-len3)>len1)
{
System.out.println("Impossible");
}
else
{
//求周长
double L = line1.getLength()+line2.getLength()+line3.getLength();
double P = L/2.0;
//求面积
double S = Math.sqrt(P*(P-line1.getLength())*(P-line2.getLength())*(P-line3.getLength()));
//结果保留两位小数
DecimalFormat df = new DecimalFormat("#0.00");
System.out.println("L = "+df.format(L)+", A = "+df.format(S));
}
}
}

    推荐阅读