Using Java, w rite a method that returns the area of a triangle using the follow
ID: 663259 • Letter: U
Question
Using Java, write a method that returns the area of a triangle using the following header:
public static double getTriangleArea(double[][] points)
The points are stored in a 3-by-2 two-dimensional array points with points[0][0] and points[0][1] for (x1, y1). The triangle area can be computed using the Heron's formula http://en.wikipedia.org/wiki/Heron%27s_formula , while using the Pythagorean Theorem you can find the distance between two points in the coordinate system. The method returns 0 if the three points are on the same line. Write a program that prompts the user to enter three points of a triangle and displays the triangle's area. Here is a sample run of the program:
Enter x1, y1, x2, y2, x3, y3: 2.5 2 5 -1.0 4.0 2.0
The area of the triangle is 2.25
Enter x1, y1, x2, y2, x3, y3: 2 2 4.5 4.5 6 6
The three points are on the same line
Explanation / Answer
import java.io.*;
import java.util.*;
class main{
public static double dis(double a, double b, double c, double d){
return Math.sqrt((c-a)*(c-a) + (d-b)*(d-b));
}
public static double area(double s, double a, double b, double c){
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter x1, y1, x2, y2, x3, y3: ");
String[] cor1 = sc.nextLine().split(" ");
double[] cor = new double[cor1.length];
for (int i = 0; i < cor1.length; i++){
cor[i] = Double.parseDouble(cor1[i]);
}
double A = dis(cor[0],cor[1],cor[2],cor[3]);
double B = dis(cor[2],cor[3],cor[4],cor[5]);
double C = dis(cor[0],cor[1],cor[4],cor[5]);
double Area = area((A+B+C)/2, A, B, C);
if (Area != 0){
System.out.println("The three points are on the same line");
}
else{
System.out.println("The area of the triangle is "+Area);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.