Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that enters 3 points in the plane (as integer x and y coordinates),
- * calculates and prints the area of the triangle composed by these 3 points.
- * Round the result to a whole number.
- * In case the three points do not form a triangle, print "0" as result. */
- import java.util.Locale;
- import java.util.Scanner;
- public class _02_TriangleArea {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Locale.setDefault(Locale.ROOT);
- Scanner scan = new Scanner(System.in);
- System.out.println("You must enters 3 points of the plane (x, y), which formed a Triangle!");
- // Here will using defined class Point:
- Point[] threePoints = new Point[3];
- for (int point = 0; point < threePoints.length; point++) {
- System.out.print("Enter next Point (2 Integer numbers for X and Y): ");
- double x = scan.nextInt();
- double y = scan.nextInt();
- threePoints[point] = new Point(x, y);
- }
- boolean isTriangle = checkGivenThreePointsIsFormTriangle(threePoints);
- long triangleArea = 0;
- if (isTriangle) {
- triangleArea = Math.round(calculateTriangleAreaFromGiven3Points(threePoints));
- }
- System.out.println("The Area of the Triangle with these 3 points is: " + triangleArea);
- }
- private static double calculateTriangleAreaFromGiven3Points(Point[] threePoints) {
- // TODO Auto-generated method stub
- double area = 0;
- for (int i = 0; i < threePoints.length; i++) {
- Point point1 = threePoints[i % 3];
- Point point2 = threePoints[(i + 1) % 3];
- Point point3 = threePoints[(i + 2) % 3];
- area += point1.getX() * (Point.minusY(point2, point3));
- }
- area = Math.abs(area / 2);
- return area;
- }
- private static boolean checkGivenThreePointsIsFormTriangle(
- Point[] threePoints) {
- // TODO Auto-generated method stub
- double[] collinearFactor = new double[2];
- for (int i = 0; i + 1 < threePoints.length; i++) {
- Point currentPoint = threePoints[i];
- Point nextPoint = threePoints[i + 1];
- double diffY = Point.minusY(nextPoint, currentPoint);
- double diffX = Point.minusX(nextPoint, currentPoint);
- collinearFactor[i] = (diffY / diffX);
- }
- if (collinearFactor[1] == collinearFactor[0]) {
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement