Java——求图形面积和周长
设计接口图形Shape、及其实现类Circle和Rectangle、工具类Show中提供两个方法showArea和showPerimeter,分别用于显示图形的周长和面积。App类中main方法中给出测试代码。Circle类中无参构造方法将半径赋值为1,Rectangle类中无参构造方法中width和length都赋值为1。如下图:
【输入形式】1或2或3,分别执行不同的代码块,得到不同结果。
import java.util.Scanner;
//定义接口Shape
interface Shape{
double area();
double perimeter();
}
//定义Circle类
class Circle implements Shape
{
private int r;
public Circle(int r)
{this.r=r;
}
public Circle()
{this.r=1;
}
public double area()
{return r*r*3.141592653589793;}
public double perimeter()
{return 2*3.141592653589793*r;}
}
//定义Rectangle类
class Rectangle implements Shape
{
private int w;
private int l;
public Rectangle(int w,int l)
{this.w=w;
this.l=l;
}
public Rectangle()
{this.w=1;
this.l=1;
}
public double area()
{return w*l;}
public double perimeter()
{return 2*(w+l);}
}
class Show {
static void showArea (Shape s)
{ System.out.println(s.area());}
static void showPerimeter (Shape s)
{System.out.println(s.perimeter());}
}
public class App {
public static void main(String[] args) {
int n;
Scanner scan=new Scanner(System.in);
n=scan.nextInt();
Shape s;
switch(n){
case 1:
s=new Circle();
Show.showArea(s);
Show.showPerimeter(s);
break;
case 2:
s=new Circle(2);
Show.showArea(s);
Show.showPerimeter(s);
break;
case 3:
s=new Rectangle(2, 6);
Show.showArea(s);
Show.showPerimeter(s);
break;
case 4:
s=new Rectangle();
Show.showArea(s);
Show.showPerimeter(s);
}
scan.close();
}
}