三角形面积 java,Java:计算三角形的面积

import java.lang.Math;

import java.awt.*

public class Triangle implements Shape

{

java.awt.Point a;

java.awt.Point b;

java.awt.Point c;

public Triangle(java.awt.Point a, java.awt.Point b, java.awt.Point c)

{

this.a = a;

this.b = b;

this.c = c;

}

public double getArea( )

{

double area;

return area = Math.abs((a-c)*(b-a)-(a-b)*(c-a));

} ...

I am trying to calculate the area of a triangle from 3 points (x,y) from a 2D Cartesian coordinate system. I'm assuming that my above formula correctly yields the area of a triangle (if not, please correct me) but my compiler says "operator - cannot be applied to java.awt.Point,java.awt.Point". I'm assuming it's saying this because you cannot subtract points from each other, but each value in the formula is either an x or y value, not a point. How can I fix my code so this would work?

Thanks!

解决方案

According to Wikipedia, you formula is correct. The article contains lots of useful and clear data.

According to the java.awt.point documentation, you should use the getX() and getY() methods, which return the coordinate value of a point.

That is,

fe56529cdaaaa9bb2f71c1ad8a1a454f.png

Should be expressed as:

Math.abs((a.getX()-c.getX())*(b.getY()-a.getY())-

(a.getX()-b.getX())*(c.getY()-a.getY()))*0.5;

It is probably not such a good practice to use point.x, because you shouldn't access an object's variable if you have a getter method that does that. This is the one aspect of separation between interface and implementation: the data point.x might be stored in many forms, not just int; The interface method assures that you'll get an int every time you use it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值