我的代码如下
//Test.java import java.util.Scanner; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); System.out.println("pls input the r of circle"); float r = input.nextFloat(); System.out.println("pls input the length of rectangle"); float length = input.nextFloat(); System.out.println("pls input the width of rectangle"); float width = input.nextFloat(); Circle circle = new Circle(r); Rectangle rectangle = new Rectangle(length,width); System.out.println("圆形的周长为" + circle.perimeter()); System.out.println("圆形的面积为" + circle.square()); System.out.println("长方形的周长为" + rectangle.perimeter()); System.out.println("长方形的面积为" + rectangle.square()); } }
Shape.java
public abstract class Shape { public abstract float square(); public abstract float perimeter(); }
Circle.java
public class Circle extends Shape{ float r; public Circle(float r0){ r = r0; } @Override public float perimeter() { // TODO Auto-generated method stub return 2*r*(float)Math.PI; } @Override public float square() { // TODO Auto-generated method stub return (float)Math.PI*r*r; } }
Rectangle.java
public class Rectangle extends Shape { public float length; public float width; public Rectangle(float length0,float width0){ width = width0; length = length0; if(length <= 0){ System.out.println("输入的长度<=0,有误"); } if(width <= 0){ System.out.println("输入的宽度<=0,请重新输入"); } } @Override public float perimeter() { // TODO Auto-generated method stub return 2*(length + width); } @Override public float square() { // TODO Auto-generated method stub return length * width; } }