Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Point class
- =============
- public class Point {
- private String name;
- private double x;
- private double y;
- public Point(String name, double x, double y) {
- this.name = name;
- this.x = x;
- this.y = y;
- }
- public Point(Point p) {
- this.name = p.name;
- this.x = p.x;
- this.y = p.y;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- 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;
- }
- public double distanceTo(Point p) {
- double dx = this.x - p.x;
- double dy = this.y - p.y;
- double d = Math.sqrt(dx * dx + dy * dy);
- return d;
- }
- @Override
- public String toString() {
- return "Point [name=" + name + ", x=" + x + ", y=" + y + "]";
- }
- }
- Triangle class
- ===============
- import java.util.Arrays;
- public class Triangle {
- private Point[] points;
- public Triangle(Point[] points) {
- this.points = points;
- }
- public Triangle(Point p1, Point p2, Point p3) {
- this.points = new Point[3];
- this.points[0] = new Point(p1);
- this.points[1] = new Point(p2);
- this.points[2] = new Point(p3);
- }
- public Point[] getPoints() {
- return points;
- }
- public Point getPoint(int i) {
- // i is 1 or 2 or 3
- return this.points[i - 1];
- }
- public void setPoint(int i, Point point) {
- // i is 1 or 2 or 3
- this.points[i - 1] = new Point(point);
- }
- public double getPerimeter() {
- // not a good way
- double l1 = points[0].distanceTo(points[1]);
- double l2 = points[1].distanceTo(points[2]);
- double l3 = points[2].distanceTo(points[0]);
- return l1 + l2 + l3;
- }
- public double getArea() {
- double l1 = points[0].distanceTo(points[1]);
- double l2 = points[1].distanceTo(points[2]);
- double l3 = points[2].distanceTo(points[0]);
- double s = (l1 + l2 + l3) / 2;
- return Math.sqrt(s * (s - l1) * (s - l2) * (s - l3));
- }
- @Override
- public String toString() {
- return "Triangle [points=" + Arrays.toString(points) + "]";
- }
- }
- Tester class
- ==============
- public class Tester {
- public static void main(String[] args) {
- Point p1 = new Point("Aa", 0, 3);
- Point p2 = new Point("Ax", 0, 0);
- Point p3 = new Point("Ag", 4, 0);
- Triangle t1 = new Triangle(p1, p2, p3);
- System.out.println(t1);
- System.out.println(t1.getPerimeter());
- System.out.println(t1.getArea());
- t1.setPoint(1, new Point("D", 3, 6));
- t1.getPoint(2).setX(4);
- t1.getPoint(2).setY(8);
- t1.setPoint(3, new Point("E", 5, 15));
- System.out.println(t1);
- System.out.println(t1.getPerimeter());
- System.out.println(t1.getArea());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement