Q:

What am I doing wrong? I keep getting NaN? (Heron's formula)

Problem:

Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.  

import java.util.Scanner;
public class AreaOfTriangle
{
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);

        final double NUM_ONE = 0.5;
        int a, b, c;
        double s, area;

        System.out.print("Enter side a: ");
        a = scan.nextInt();

        System.out.print("Enter side b: ");
        b = scan.nextInt();

        System.out.print("Enter side c: ");
        c = scan.nextInt();

        s = NUM_ONE * (a + b + c);

        area = Math.sqrt(s*(s-a)*(s-b)*(s-c));

        System.out.println("\nThe area of the triangle = " + area);
    }
}

A:

The formula is correct, but s*(s-a)*(s-b)*(s-c) could end up being very slightly negative depending on the inputs (due to floating point imprecision). You should test this prior to taking the sqrt, and return zero in that instance.
Math.sqrt on a negative number will return NaN.

A:

Because in some cases with your code you end up with a negative value in your sqrt call:
 a = 1;
 b = 2;
 c = 5;

 s = NUM_ONE * (a + b + c);

Here s = 4.0 and then your sqrt parameter is 4*3*2*-1 which is negative
Should you use Math.sqrt(Math.abs(...)) instead ?

