Reputation: 9
I'm attempting to write Java code that takes the vertices of a triangle (which will be user input) and outputs the area of said triangle. I'm getting NaN
as a response. Should I be changing my types into floats? Am I taking a longer route to try and solve this problem?
Formulas used are Distance formula and Heron's formula.
import java.util.Scanner;
public class TriangleArea {
public static void main(String[]args){
Scanner user = new Scanner(System.in);
System.out.println("To compute the area of a triangle, please input a point in a vertex when prompted");
System.out.println("Please input X of the first vertex: x ");
double firstVertexX = user.nextDouble();
System.out.println("Please input Y of the first vertex: y ");
double firstVertexY = user.nextDouble();
System.out.println("Please input X of the second vertex: x");
double secondVertexX = user.nextDouble();
System.out.println("Please input Y of the second vertex: y ");
double secondVertexY = user.nextDouble();
System.out.println("Please input X of the third vertex: x");
double thirdVertexX = user.nextDouble();
System.out.println("Please input Y of the third vertex: y");
double thirdVertexY = user.nextDouble();
double sideOneX = Math.pow(firstVertexX * 1, 2) - Math.pow(secondVertexX * 2, 2);
double sideOneY = Math.pow(firstVertexY * 1, 2) - Math.pow(secondVertexY * 2, 2);
double sideOne = Math.pow(sideOneX + sideOneY, .5);
double sideTwoX = Math.pow(secondVertexX * 1, 2) - Math.pow(thirdVertexX * 2, 2);
double sideTwoY = Math.pow(secondVertexY * 1, 2) - Math.pow(thirdVertexY * 2, 2);
double sideTwo = Math.pow(sideTwoX + sideTwoY, .5);
double sideThreeX = Math.pow(thirdVertexX * 1, 2) - Math.pow(firstVertexX * 2, 2);
double sideThreeY = Math.pow(thirdVertexY * 1, 2) - Math.pow(firstVertexY * 2, 2);
double sideThree = Math.pow(sideThreeX + sideThreeY, .5);
double s = (sideOne + sideTwo + sideThree)/2;
double areaStepOne = (s - sideOne) * (s - sideTwo) * (s - sideThree);
double areaStepTwo = s * areaStepOne;
double area = Math.pow(areaStepTwo, .5);
System.out.println("The area of the triangle is " + area + ".");
System.out.println("The area of the triangle is " + area);
}
}
Upvotes: 0
Views: 535
Reputation:
I advise you to use the simpler analytic formula
|(X2 - X0) (Y1 - Y0) - (X1 - X0) (Y2 - Y0)| / 2
Not taking the absolute value, the sign tells you if the triangle is clockwise or counterclockwise.
Upvotes: 1
Reputation: 1584
The issue is a miscalculation.
The length of a line segment from (x1,y1) to (x2,y2) is sqrt( (x1-x2)^2 + (y1-y2)^2 ).
What you are calculating instead is: sqrt( x1^2 - (x2*2)^2 + y1^2 - (y2*2)^2 ). And this can be negative, giving you the NaNs.
I'd change the lines to be like:
double sideOneX = firstVertexX - secondVertexX;
double sideOneY = firstVertexY - secondVertexY;
double sideOne = Math.sqrt(sideOneX * sideOneX + sideOneY * sideOneY);
(You can just use Math.sqrt(v)
instead of Math.pow(v, .5)
.)
Upvotes: 1