Demonstrate the Method Overloading feature
of Object Oriented
Programming using example of “calculate Volume
of given objects” program.
Create a Volume class
called by main class which contains method volume that
calculate the
volume of cube or cuboid or cylinder, depending on number of
parameters. Read all the inputs from user. Result has to be printed
in main class.
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
class
Volume
{
double
volume(double
l)
{
return
l*l*l;
}
double
volume(double
r,double
h)
{
return
3.14*r*r*h;
}
double
volume(double
l,double
w,double
h)
{
return
l*w*h;
}
void
printMenu()
{
System.out.println("Select
One to Calculate Volume or Exit");
System.out.println("1)
Cube");
System.out.println("2)
Cuboid");
System.out.println("3)
Cylinder");
System.out.println("4)
Exit");
}
}
public
class
lab3A1
{
public
static
void
main(String args[]) throws
NumberFormatException, IOException
{
Volume
v=new
Volume();
int
option;
boolean
exit=false;
BufferedReader
br =new
BufferedReader(new
InputStreamReader(System.in));
double
answer,l,w,h,r;
do
{
v.printMenu();
try
{
option=Integer.parseInt(br.readLine().toString());
}
catch(Exception
e)
{
option=5;
System.out.println(e);
}
if(option==1)
{
System.out.println("Enter
the Cube Length:");
answer=v.volume(Double.parseDouble(br.readLine().toString()));
System.out.println("The
Volume of Cube is:"+answer);
}
else
if(option==2)
{
System.out.println("Enter
the Cuboid Length:");
l=Double.parseDouble(br.readLine().toString());
System.out.println("Enter
the Cuboid Width:");
w=Double.parseDouble(br.readLine().toString());
System.out.println("Enter
the Cuboid Height:");
h=Double.parseDouble(br.readLine().toString());
answer=v.volume(l,w,h);
System.out.println("The
Volume of Cuboid is:"+answer);
}
else
if(option==3)
{
System.out.println("Enter
the Cylinder Radius:");
r=Double.parseDouble(br.readLine().toString());
System.out.println("Enter
the Cylinder Height:");
h=Double.parseDouble(br.readLine().toString());
answer=v.volume(r,h);
System.out.println("The
Volume of Cylinder is:"+answer);
}
else
if(option==4)
{
exit=true;
System.out.println("Closing
Program");
}
else
{
System.out.println("Invalid
Option");
}
}while(!exit);
}
}
No comments:
Post a Comment