Pages

This blog is under construction

Sunday, November 11, 2018

Define the Triangle class with three sides. In a triangle, the sum of any two sides is greater than the other side. The Triangle class must adhere to this rule. Create the IllegalTriangleException class by extending the Exception class, and modify the constructor of the Triangle class to throw an IllegalTriangleException object if a triangle is created with sides that violate the rule, as follows: /** Construct a triangle with the specified sides */ public Triangle(double side1, double side2, double side3) throws IllegalTriangleException { // Implement it }

JAVA Code:                                                                                                          Topic: Exception Handling

 package javaapplication34;
 import java.util.Scanner;
 class Triangle {
                          private double side1=1.0;
                          private double side2=1.0;
                          private double side3=1.0;
         
  public Triangle(double side1, double side2, double side3) throws IllegalTriangleException
         {        if(side1+side3 <= side2 || (side1 + side2) <= side3 || (side2 + side3) <= side1)
                  { throw new IllegalTriangleException();
                  }
                 else   {
                      this.side1=side1;
                      this.side2=side2;
                     this.side3=side3;
                       }
        }
     }

 class IllegalTriangleException extends Exception
           {
               IllegalTriangleException()
                     { super("Exception: Invalid Triangle Side Numbers");
                     }
           }

 public class javaapplication34 { public static void main(String[] args)
     {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter Three Double Side: ");
       double side1 = input.nextDouble();
       double side2 = input.nextDouble();
      double side3 = input.nextDouble();
   try{
           Triangle tr=new Triangle( side1, side2, side3);
            System.out.println("Valid triangle sides");
     }
catch(IllegalTriangleException e)
{
System.out.println(e);
 }
 }
 }
OUTPUT:
custom exception definition



No comments:

Post a Comment