#【JAVA初學者】 關於一道JAVA的題目
主要實現類:
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;
}
}
如果後續還有再添加什麼形狀,如三角形梯形,多邊形啥的,直接繼續實現形狀接口就好。