Skip to content

Commit

Permalink
2.1. Рефакторинг - Площадь треугольника.
Browse files Browse the repository at this point in the history
  • Loading branch information
Temzor committed Oct 31, 2023
1 parent 9a137c1 commit 3c4f804
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/main/java/ru/j4j/oop/Point.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package ru.j4j.oop;

import static java.lang.Math.sqrt;
import static java.lang.Math.pow;

public class Point {
private final int x;
private final int y;

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

public double distance(Point that) {
return sqrt(pow(this.x - that.x, 2) + pow(this.y - that.y, 2));
}
}
34 changes: 34 additions & 0 deletions src/main/java/ru/j4j/oop/Triangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ru.j4j.oop;

import static java.lang.Math.*;

public class Triangle {
private Point ab;
private Point bc;
private Point ca;

public Triangle(Point ab, Point bc, Point ca) {
this.ab = ab;
this.bc = bc;
this.ca = ca;
}

public double semiPerimeter(double a, double b, double c) {
return (a + b + c) / 2;
}

public boolean exist(double ab, double ac, double bc) {
return ab + ac > bc && ac + bc > ab && ab + bc > ac;
}

public double area() {
double ab = this.ab.distance(this.bc);
double bc = this.ab.distance(this.ca);
double ca = this.bc.distance(this.ca);
if (exist(ab, bc, ca)) {
double p = semiPerimeter(ab, bc, ca);
return sqrt(p * (p - ab) * (p - bc) * (p - ca));
}
return -1;
}
}
40 changes: 40 additions & 0 deletions src/test/java/ru/j4j/oop/TriangleTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package ru.j4j.oop;

import static org.assertj.core.api.Assertions.*;

import org.junit.jupiter.api.Test;

class TriangleTest {
@Test
public void when00and40and04Then8() {
Point a = new Point(0, 0);
Point b = new Point(4, 0);
Point c = new Point(0, 4);
Triangle triangle = new Triangle(a, b, c);
double rsl = triangle.area();
double expected = 8;
assertThat(rsl).isCloseTo(expected, offset(0.001));
}

@Test
public void when00and00and04Then1() {
Point a = new Point(0, 0);
Point b = new Point(0, 0);
Point c = new Point(0, 4);
Triangle triangle = new Triangle(a, b, c);
double rsl = triangle.area();
double expected = -1;
assertThat(rsl).isCloseTo(expected, offset(0.001));
}

@Test
public void negativeTest() {
Point a = new Point(0, 0);
Point b = new Point(0, 0);
Point c = new Point(0, 4);
Triangle triangle = new Triangle(a, b, c);
double rsl = triangle.area();
double expected = -1;
assertThat(rsl).isEqualTo(expected);
}
}

0 comments on commit 3c4f804

Please sign in to comment.