(Geometry: area of a triangle) Write a program that prompts the user to enter three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area. The formula for computing the area of a triangle is
s = (side1 + side2 + side3)/2;
area = √2s(s - side1)(s - side2)(s - side3) Here is a sample run:
Solution
/*
(Geometry: area of a triangle) Write a program that prompts the user to enter
three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.
*/
import java.util.Scanner;
public class Exercise_02_19
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Prompt the user to enter three points
System.out.print("Enter x1 point for a triangle: ");
double x1 = input.nextDouble();
System.out.print("Enter y1 point for a triangle: ");
double y1 = input.nextDouble();
System.out.print("Enter x2 point for a triangle: ");
double x2 = input.nextDouble();
System.out.print("Enter y2 point for a triangle: ");
double y2 = input.nextDouble();
System.out.print("Enter x3 point for a triangle: ");
double x3 = input.nextDouble();
System.out.print("Enter y3 point for a triangle: ");
double y3 = input.nextDouble();
// Compute the area of a triangle
double side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
double side2 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
double side3 = Math.pow(Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2), 0.5);
double s = (side1 + side2 + side3) / 2;
double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
// Display result
System.out.println("The area of the triangle is " + area);
}
}
Output
Enter x1 point for a triangle: 12.5
Enter y1 point for a triangle: 13.6
Enter x2 point for a triangle: 18.6
Enter y2 point for a triangle: 13.6
Enter x3 point for a triangle: 14.4
Enter y3 point for a triangle: 17.9
The area of the triangle is 13.114999999999995));
If you have any doubts or questions, please let me know.