Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Area of Triangle, Java

Tags:

java

area

I'm trying to build an app which computes the area of a triangle, as per my homework assignment. Not quite sure where I'm going wrong, but I input the lengths of the triangle and would like the proper area displayed according to Heron's formula: sqrt (s(s-a) (s-b) (s-c)). All I'm getting for output is -0.0. Here is the code:

import java.lang.Math;
public class Formula
{
    double area; double s;
    public double findArea(double sideA, double sideB, double sideC)
    { 
        s = 1/2 * (sideA + sideB + sideC);
        area = Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC));
        System.out.println("The area of the triangle is " + area);
        return area;
    }
}

And then I have another file for the main args

import java.util.Scanner;

public class findTriangleArea {

    /**
     * @param args
     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub
        Formula triangle = new Formula();
        double a,b,c;

        // input triangle lengths a, b, c 
        Scanner inputTriangle = new Scanner(System.in);
        System.out.println("Please enter triangle side a");
        a = inputTriangle.nextDouble();
        System.out.println("Please enter triangle side b");
        b = inputTriangle.nextDouble();
        System.out.println("Please enter triangle side c");
        c = inputTriangle.nextDouble();
        triangle.findArea(a, b, c);
    }
}
like image 364
user1294476 Avatar asked Apr 24 '12 00:04

user1294476


People also ask

How do you find area of triangle with 3 sides in Java?

If the three sides of the triangle are known, we can make use of the formula s ( s − a ) ( s − b ) ( s − c ) \sqrt{s(s-a)(s-b)(s-c)} s(s−a)(s−b)(s−c) which is known as the Heron's formula.

How do you find area with a triangle?

Area of a Triangle = A = ½ (b × h) square units where b and h are the base and height of the triangle, respectively. Now, let's see how to calculate the area of a triangle using the given formula.

How do you find the area of an isosceles triangle in Java?

Area_of_Isosceles_Triangle= (1 * b * h) / 2; // It is a formula for calculating the area of Isosceles Triangle. return(Area_of_Isosceles_Triangle);


1 Answers

1/2 is being computed in integer arithmetic, so like with all integer division, it's truncated -- in this case, to 0. Just write 0.5 and you'll be fine.

like image 166
Louis Wasserman Avatar answered Oct 11 '22 21:10

Louis Wasserman