jeudi 5 mars 2015

Access area from vertices of triangle



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);

}
}



Aucun commentaire:

Enregistrer un commentaire