In: Computer Science
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It will return true if and only if the sum of side1+ side2 is greater than side3 AND the sum side2+side3 is greater than side1 AND the sum of side1+ side3 is greater than side2. If any of those three conditions is not met, the method will create and throw an IllegalTriangleSideException. Add a main method to create and check two to three different triangles.
*EDIT: Programming Language: Java*
IllegalTriangleSideException.java :
//Java class which extends Exception
public class IllegalTriangleSideException extends Exception {
//constructor
public IllegalTriangleSideException(String ex)
{
super(ex);//call base call
constructor
}
}
*****************************
Triangle.java :
//Java class
public class Triangle {
// double variables
private double side1;
private double side2;
private double side3;
//constructor
public Triangle(double s1,double s2,double s3)
{
side1=s1;
side2=s2;
side3=s3;
}
//method to check sides
public boolean checkSides() throws
IllegalTriangleSideException
{
//checking three sides of the
triangle
if((side1+ side2)>side3
&& (side2+ side3)>side1 && (side1+
side3)>side2)
{
//if above
criteria match then
return
true;//return true
}
else {
throw new
IllegalTriangleSideException("Invalid triangle sides");
}
}
}
**********************************************
TriangleTest.java :
//Java class
public class TriangleTest {
//main() method
public static void main(String[] args) {
//try catch block
try {
//object of
Triangle class
Triangle t=new
Triangle(6,5,4);
//calling method
to check Triangle
System.out.println(t.checkSides());
}
catch(Exception ex)
{
System.out.println("Exception :"+ex);
}
}
}
===========================================
Screen showing details when condition is satisfied :
Screen showing details when condition is not satisfied :