I am confused with the technical jargon that was involved in this question:
Given three straight lines a, b & c. They will be able to form a
triangle provided that sum of any two lines is always greater than the
third line (i.e. a + b > c and b + c > a and a + cb). Write a Java class Triangle with the following:
Attributes: length of the three sides of the triangle
Behaviour:
- Constructor that sets the length of the three sides to the values passed in. The constructor should throw an InvalidValueException
object when the values are not able to form a triangle.
- findArea() method to calculate the area of the Triangle object using the formula area = a +b+c
The code that I came up with is this:
package question3_test;
import java.awt.event.*;
import java.math.*;
public class Triangle_getvalues
{
private int side1, side2, side3;
private double area;
private String message;
public int getSide1()
{
return side1;
}
public void setSide1(int s1)
{
side1 = s1;
}
public int getSide2()
{
return side2;
}
public void setSide2(int s2)
{
side2 = s2;
}
public int getSide3()
{
return side3;
}
public void setSide3(int s3)
{
side3 = s3;
}
public double findArea(int side_1, int side_2, int side_3)throws InvalidValueException
{
int s, a, b,c;
a = side_1;
b = side_2;
c = side_3;
s = ((a + b + c)/2);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
//area =
return area;
}
public void validateTriangle(int sidea, int sideb, int sidec) throws InvalidValueException
{
try
{
if((sidea + sideb > sidec)||(sideb + sidec > sidea)||(sidea + sidec > sideb))
{
findArea(side1,side2,side3);
}
}
catch(InvalidValueException excep)
{
message = excep.getMessage();
}
}
}
class InvalidValueException extends Exception
{
public InvalidValueException()
{
super("These values cannot form a valid triangle");
}
}
What I would like to know is not that I am missing something (do let me know if I am missing something though) but main objective of asking here is, is this the right way to answer this question?
You have the right idea. You’re just not combining your code to match your assignment.
A class constructor would look like this.
Your validateTriangle method shouldn’t try to both throw the InvalidValueException and catch the InvalidValueException. Choose one or the other.
Your validateTriangle method doesn’t need to call or perform the findArea method. You just need to determine whether or not the input lengths make a valid triangle.
Here’s how it should work: