问题描述
解决方案
主要实现类:
package com.test;
/**
* 计算使用率
*/
public class Domain {
private static double maxArea;//最外边矩形的面积
private static double userArea;//已使用的面积
private static double usageRate;//使用率
public static void main(String[] args) {
double[] db1 = {400.0, 50.0};
double[] db2 = {10.0};
double[] db3 = {10.0, 20.0};
double[] db4 = {5.0, 15.0};
double[] db5 = {23.5};
maxArea = getArea(db1);
userArea = getArea(db2)
+ getArea(db3)
+ getArea(db4)
+ getArea(db5);
usageRate = userArea / maxArea;
System.out.println(usageRate);
}
public static double getArea(double[] db){
if(null == db || db.length == 0){
return 0;
}
int len = db.length;
Shape shape = null;
if(len == 1){
shape = new Round(db[0]);
}
if(len == 2){
shape = new Rectangle(db[0], db[1]);
}
return shape.getArea();
}
}
形状的接口:
package com.test;
/**
* 形状
*/
public interface Shape {
//面积
double area = 0;
//获取形状的面积
public double getArea();
}
矩形类型,实现形状接口:
package com.test;
/**
* 矩形,包括长方形和正方形
*/
public class Rectangle implements Shape{
private double lenth;//长
private double width;//宽
Rectangle(){
}
Rectangle(double lenth, double width){
this.lenth = lenth;
this.width = width;
}
public double getArea() {
//计算长方形面积
return this.lenth * this.width;
}
public double getLenth() {
return lenth;
}
public void setLenth(double lenth) {
this.lenth = lenth;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
}
圆形类,实现形状接口:
package com.test;
/**
* 圆形
*/
public class Round implements Shape {
private static final double PI = 3.14;
private double r;//圆形的半径
Round(){
}
Round(double r){
this.r = r;
}
public double getArea() {
return PI * r * r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
如果后续还有再添加什么形状,如三角形梯形,多边形啥的,直接继续实现形状接口就好。
时间: 2025-01-19 01:55:46