Math.sqrt causing general havoc
The program needs to take 3 x values followed by 3 y values to create 3 points that form a triangle, then calculate the area of the triangle. I'm pretty convinced the logic is right, and it should be an easy fix.
public class ComputeTriangle
public static void main(Stringargs)
Scanner input = new Scanner(System.in);
System.out.print("Please input the three points for a triangle: ");
double x1, x2, x3, y1, y2, y3, side1, side2, side3, s, area, calculate;
x1 = input.nextDouble();
x2 = input.nextDouble();
x3 = input.nextDouble();
y1 = input.nextDouble();
y2 = input.nextDouble();
y3 = input.nextDouble();
side1 = (x2-x1)/(y2-y1);
side2 = (x3-x1)/(y3-y1);
side3 = (x3-x2)/(y3-y2);
s = (side1 + side2 + side3)/2;
area = Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
System.out.println("The area of the triangle is: " + area);
Please input the three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4
The area of the triangle is: NaN
Press any key to continue . . .
Can anyone help me get rid of this 'Not a Number' runtime error?
Re: Math.sqrt causing general havoc
The javadoc says that "If the argument is NaN or less than zero, the result is NaN." You are probably passing the method a less than zero argument. You can check that out by printing every variable you have.
Also I am not sure about your logic. The sides should be the euclidean distance between points. And the formula for computing the euclidean distance is;
Point 1 at (x1, y1) and Point 2 at (x2, y2).
xd = x2 - x1
yd = y2 - y1;
Distance = Square Root (xd ^2 + yd ^2)
Hope it helps.