面向对象 (5)计算棱柱体积可换底
作者:互联网
题目:计算棱柱体积可换底
一、源程序
1、Test.java
/**计算棱柱体积可换底 * 9个类 */ package w29; import java.util.Scanner; public class Test { public static void main(String[] args) { while(true){ Scanner reader = new Scanner(System.in); System.out.println("请输入柱体底的形状:r(矩形);s(正方形);t(梯形);T(三角形);c(圆形)。"); char c = reader.next().charAt(0); Factory factory = new Factory(); Shape shape; Column column = new Column(factory.getShape(c),reader.nextDouble()); System.out.println("柱体的体积"+column.getVolume()); } } }
2、Factory.java
package w29; //工厂类 import java.util.Scanner; public class Factory { protected Shape getShape(char c){ Scanner reader = new Scanner(System.in); Shape shape = null; switch(c){ case 'r':System.out.println("请输入矩形底的长和宽、柱体的高");shape = new Rectangle(reader.nextDouble(),reader.nextDouble());break; case 's':System.out.println("请输入正方形底的边、柱体的高");shape = new Square(reader.nextDouble());break; case 't':System.out.println("请输入梯形底的上下底和高、柱体的高");shape = new trapezium(reader.nextDouble(),reader.nextDouble(),reader.nextDouble());break; case 'T':System.out.println("请输入三角形底的三边、柱体的高");shape = new Triangle(reader.nextDouble(),reader.nextDouble(),reader.nextDouble());break; case 'c':System.out.println("请输入圆形底的半径、柱体的高");shape = new Circle(reader.nextDouble());break; } return shape; } }
3、Shape.java
package w29; //形状接口 public interface Shape { double getArea(); }
4、Rectangle.java
package w29; //矩形类 public class Rectangle implements Shape { double width,length; public Rectangle(double width,double length){ this.width = width; this.length = length; } public double getArea() { return width*length; } }
5、Square.java
package w29; //正方形类 public class Square extends Rectangle { public Square(double side) { super(side, side); } public double getArea() { return width*length; } }
6、trapezium.java
package w29; //梯形类 public class trapezium extends Rectangle { double height; public trapezium(double up, double down, double height) { super(up, down); this.height = height; } public double getArea() { return (width+length)*height/2; } }
7、Triangle.java
package w29; //三角形类 public class Triangle implements Shape { double a,b,c; public Triangle(double a, double b, double c) { super(); this.a = a; this.b = b; this.c = c; } public double getArea() { double sum = (a+b+c)/2; return Math.sqrt(sum*(sum-a)*(sum-b)*(sum-c)); } }
8、Circle.java
package w29; //圆形类 public class Circle implements Shape { double radius; public Circle(double radius) { super(); this.radius = radius; } public double getArea() { // TODO Auto-generated method stub return radius*radius*3.14; } }
9、Column.java
package w29; //柱体类 public class Column { Shape shape; double high; public Column(Shape shape, double high) { super(); this.shape = shape; this.high = high; } public double getVolume(){ return shape.getArea()*high; } }
二、成功界面截图
标签:棱柱,java,double,面向对象,shape,reader,可换底,public,nextDouble 来源: https://www.cnblogs.com/wangxiangyue/p/11609235.html