Method returns value of 0
Hey everyone! Java beginner here. So I was writing this method which gets the area of a right-angled triangle. The sides (a b c) will be called by the constructor Triangle. My problem is that the program compiles well enough however the value returned for the area is 0. I tried initializing the variables but to no avail. Can anyone please guide me as to where the problem lies. I'm not sure its a problem with the syntax since the program compiles but probably the error lies somewhere with the logic. Thanks Below is the code:
Code:
import java.util.*;
public class Triangle
{
double a=0, b=0, c=0;
double area =0;
public Triangle (double side1, double side2, double side3)
{
this.a = side1;
this.b = side2;
this.c = side3;
}
public double getArea()
{
if (a>b && b>c)
{
this.area = ((b*c)/2);
}
else if (b>a && a>c)
{
this.area = ((a*c)/2);
}
else if (c>a && a>b)
{
this.area = ((a*b)/2);
}
return this.area;
}
}
Re: Method returns value of 0
Stick some debug code (println() statements) into the getArea method, first printing out the values of a, b and c, and then to see which path it is going through in that if/else statement.
Re: Method returns value of 0
Always add an ending else statement at the end of a chain of if/else if that prints out why none of the above if conditions were true.
Re: Method returns value of 0
your condition in the method getArea() does not cover all the possibilities.
they should be like this:
public double getArea()
{
if (a>b && a>c)
{
this.area = ((b*c)/2);
}
else if (b>a && b>c)
{
this.area = ((a*c)/2);
}
else if (c>a && c>b)
{
this.area = ((a*b)/2);
}
return this.area;
}
hope it helps
by the way, if you write the code like this, you must ensure that the triangle you input to the system is RT. otherwise, your result will be wrong.
Re: Method returns value of 0
Please Edit your post and wrap your code with
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
An ending else statement would have shown that. It's always a good idea to add the ending else statement to catch unexpected errors.
Re: Method returns value of 0
Hey all thx for the replies. As you rightly pointed out the if/else statements didn't cover all the possibilities and in this case when I called the constructor none of the conditions were satisfied hence the error. Btw Norm thx for the advice will be using it from now on. Hava a good day.