settingsAccountsettings
Menusettings

Q: Triangle area with given x and y as coordinates - Java Task

+6 votes

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.

Examples:

calcualte triangle area by given coordinates x and y

asked in Java category by user eiorgert
edited by user golearnweb

1 Answer

0 votes
 
Best answer

You can go HERE: http://www.mathopenref.com/coordtrianglearea.html and use the formula described there:

java coordinates in a triangle - calcualte the area

and here's my solution:

import java.util.Scanner;

public class Pr_02_TriangleArea {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String[] sideOne = scanner.nextLine().split(" ");
        String[] sideTwo = scanner.nextLine().split(" ");
        String[] sideThree = scanner.nextLine().split(" ");

        int aX = Integer.parseInt(sideOne[0]);
        int aY = Integer.parseInt(sideOne[1]);

        int bX = Integer.parseInt(sideTwo[0]);
        int bY = Integer.parseInt(sideTwo[1]);

        int cX = Integer.parseInt(sideThree[0]);
        int cY = Integer.parseInt(sideThree[1]);

        //CHECK IF CORRECT // System.out.printf("%d %d %d %d %d %d",aX,aY,bX,bY,cX,cY);

        //USING THE FORULA FROM: mathopenref.com/coordtrianglearea.html
        //WHICH IS: |((aX*(bY-cY) +bX*(cY-aY)+cX*(aY-bY)))/2|

        int areaTriangle = ((aX * (bY - cY) + bX * (cY - aY) + cX * (aY - bY))) / 2;
        System.out.println("The area of the triangle is: " + Math.abs(areaTriangle));
    }
}

 

answered by user golearnweb
edited by user golearnweb
...