Write a program that prompts the user to enter three points

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 = squareroot s(s - side1)(s - side2)(s - side3) Here is a sample run: Enter three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4 The area of the triangle is 33.6

Solution

The following code gives you the required functionality;

/* package whatever; // don\'t place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;

/* Name of the class has to be \"Main\" only if the class is public. */
class Ideone
{
   public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
       Scanner scanner = new Scanner(System.in);
       DecimalFormat df = new DecimalFormat(\"#.#\");
      
       double x1, x2, x3, y1, y2, y3, side1, side2, side3, s, area;
       System.out.print(\"Enter three points for a triangle: \");
       x1 = scanner.nextDouble();
       y1 = scanner.nextDouble();
       x2 = scanner.nextDouble();
       y2 = scanner.nextDouble();
       x3 = scanner.nextDouble();
       y3 = scanner.nextDouble();
      
       //calculating triangles sides
       side1 = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1, 2));
       side2 = Math.sqrt(Math.pow(x2-x3,2) + Math.pow(y2-y3, 2));
       side3 = Math.sqrt(Math.pow(x3-x1,2) + Math.pow(y3-y1, 2));
      
       s = (side1 + side2 + side3)/2;
      
       area = Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
      
       System.out.println(\"The area of the triangle is \"+df.format(area));
      
   }//end of main function
}//end of class

Input:

1.5 -3.4 4.6 5 9.5 -3.4

Output:

Enter three points for a triangle: The area of the triangle is 33.6

Code URL:

http://ideone.com/0Bgygb

Hope it helps, do give your response.

 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 are

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site