The purpose of this lab is
to learn method overloading in Java.
Instructions:
Your GTA will lead you through the following:
The skeleton code provided below finds the area of a polygon given its radius, height, etc respectively. Lines 1 through 4 prompts the user to
choose a polygon following which we use a switch case to prompt the user for polygon specific information. You will need to write two other getArea() methods(overload the getArea() method) in addition to what is provided below as well as complete the switch case statement. Area equations,
1. Area of a circle = pi * radius * radius
2. Area of a rectangle/square = length * width
3. Area of a Trapeziod = 0.5 * height * (base1 + base2)
public class Polygons
{
public static void main(String [] args)
{
Polygons p = new Polygons(); //Line 1
Scanner input = new Scanner(System.in); //Line 2
System.out.println("Polygons: circle, square, rectangle, trapezoid"); //Line 3
System.out.print("Choose a polygon: "); //Line 4
switch(input.next().charAt(0))
{
case 'c':case 'C': //Circle
{
System.out.print("Enter the radius: ");
System.out.print("The area is "+p.getArea(input.nextInt()));
break;
}
case 's':case 'S':case 'r':case 'R': //Square or Rectangle
{
}
case 't':case 'T': //Trapezoid
{
}
default:
{
System.out.print("Invalid polygon!");
break;
}
}
input.close();
}
public double getArea(int radius)
{
return (Math.PI * radius * radius);
}
}
Sample output will look like,
Polygons: circle, square, rectangle, trapezoid
Choose a polygon: circle
Enter the radius: 7
The area is 153.93804002589985
Polygons: circle, square, rectangle, trapezoid
Choose a polygon: trapezoid
Enter the height, base 1 and base 2: 15 12 8
The area is 150.0
© 2009 CSU