代码实现
- Shape类
abstract class Shape {
public abstract double shapeC(); //周长
public abstract double shapeS(); //面积
}
- Circle类
import static java.lang.Math.PI;
public class Circle extends Shape {
private double r; //半径
public void setR(double r){
this.r = r;
}
public double getR(){
return this.r;
}
public double shapeC(){
return PI*2*r;
}
public double shapeS(){
return PI*r*r;
}
public Circle(double r){
this.setR(r);
}
}
- Rectangle类
public class Rectangle extends Shape {
private double l; //长
private double w; //宽
public void setL(double l) {
this.l = l;
}
public double getL() {
return this.l;
}
public void setW(double w) {
this.w = w;
}
public double getW() {
return this.w;
}
public double shapeC(){
return (l+w)*2;
}
public double shapeS(){
return l*w;
}
public Rectangle(double l,double w){
this.setL(l);
this.setW(w);
}
}
- Square类
public class Square extends Shape {
private double f; //边长
public void setF(double f){
this.f = f;
}
public double getF(){
return this.f;
}
public double shapeC(){
return 4*f;
}
public double shapeS(){
return Math.pow(f,2);
}
public Square(double f){
this.setF(f);
}
}
- Test类
import java.util.Scanner;
public class Text {
public static void main(String[] args) {
boolean flag = true;
while(flag){
System.out.println("======请选择需要计算的图形======");
System.out.println(" (1)圆 形");
System.out.println(" (2)长方形");
System.out.println(" (3)正方形");
System.out.println(" (4)退 出");
System.out.println("=============================");
System.out.println("请输入编号:");
Scanner num = new Scanner(System.in);
int n = num.nextInt();
switch(n){
case 1: {
System.out.println("请输入圆的半径:");
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
Circle circle = new Circle(a);
System.out.println("圆的半径为:" + circle.getR());
System.out.println("圆的周长为:" + circle.shapeC());
System.out.println("圆的面积为:" + circle.shapeS());
}
break;
case 2:{
System.out.println("请输入长方形的边长:");
Scanner s = new Scanner(System.in);
System.out.println("输入长方形的长:");
double l = s.nextDouble();
System.out.println("输入长方形的宽:");
double w = s.nextDouble();
Rectangle rectangle = new Rectangle(l,w);
System.out.println("长方形的长为:"+rectangle.getL());
System.out.println("长方形的宽为:"+rectangle.getW());
System.out.println("长方形的周长为:"+rectangle.shapeC());
System.out.println("长方形的面积为:"+rectangle.shapeS());
}
break;
case 3:{
System.out.println("请输入正方形的边长:");
Scanner s = new Scanner(System.in);
double f = s.nextDouble();
Square square = new Square(f);
System.out.println("正方形的边长为:"+square.getF());
System.out.println("正方形的周长为:"+square.shapeC());
System.out.println("正方形的面积为:"+square.shapeS());
}
break;
case 4:{
flag = false;
}
break;
}
}
}
}
测试结果
希望对你有帮助,觉得有用的话,期待你的关注。