Monday, August 19, 2019

Menu Based Function Overloading Program To Display Area



BlueJ program on function overloading. Function overloading is one type of polymorphism.


Define a class TraingleArea that contains the overloaded area methods – one accepts the length and breadth of a triangle as parameter. The other area method accepts the three sides of a triangle.

The two formulas of computing the area are:
Area1 = ½*base*height
Area2 = Square Root of s(s-a)*s(s-b)*s(s-c)
Where s=(a+b+c)/2 and a,b,c are three sides


import java.util.*;
class TraingleArea
{
Scanner sc=new Scanner(System.in);
public void takeDatas()
{
    int choice, a,b,c,base,height;
    double area1;


System.out.print("\nEnter Choice (1 for Area1 and 2 for Area2):");
choice=sc.nextInt();
switch(choice)
{
     case 1:
            System.out.print("\nEnter Base:");
            base=sc.nextInt();
            System.out.print("\nEnter Height:");
            height=sc.nextInt();
            area1=area(base,height);
            System.out.print("\nArea of triangle as per first formula = "+area1);
            break;
           
     case 2:
           System.out.print("\nEnter 1st Side:");
           a=sc.nextInt();
           System.out.print("\nEnter 2nd Side:");
            b=sc.nextInt();
            System.out.print("\nEnter 3rd Side:");
            c=sc.nextInt();
            area1=area(a,b,c);
            System.out.print("\nArea of triangle as per second formula = "+area1);
            break;
     default:
              System.out.print("\nWrong Choice.");
 }
}
 private double area(int a,int b)
 {
      double r;
      r=1/2.0*a*b;
      return r;
  }
 
  private double area(int a,int b,int c)
 {
      double r;
      double s;
      s=(a+b+c)/2.0;
      s=s*(s-a)*s*(s-b)*s*(s-c);
      r=Math.sqrt(s);
      return r;
  }   
   
public static void main(String args[])throws Exception
{
TraingleArea ob=new TraingleArea ();
ob.takeDatas();
}
}


Related Post: BlueJ Menu Based Programs

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner