设计一个扩展 GeometricObject 的名为 Triangle 的类(代码如下)。Triangle 类包含: • 三个名为side1、side2 和side3 的双精度数据字段,默认值1.0 表示三角形的三个边。• 创建默认三角形的无参数构造函数。• 创建具有指定边1、边2 和边3 的三角形的构造函数。• 所有三个数据字段的访问器方法。• 名为getArea() 的方法返回此三角形的面积。• 名为getPerimeter() 的方法返回此三角形的周长。• 一个名为 toString() 的方法,它返回三角形的字符串描述。
public class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
public GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with the specified color
* and filled value */
public GeometricObject(String Color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/** Return filled. Since filled is boolean,
its get method is named isFilled */
public boolean isFilled() {
return filled;
}
/** Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
/** Return a string representation of this object */
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
}
休息
public class Triangle extends GeometricObject {
double side1 = 1.0;
double side2 = 1.0;
double side3 = 1.0;
public Triangle() {
side1=0.0;
side2=0.0;
side3=0.0;
}
public Triangle(double a, double b, double c) {
side1 = a;
side2 = b;
side3 = c;
}
public void show() {
System.out.println(side1+","+side2+","+side3+",");
}
public void calcArea(){
double s = 0.0, Num = 0.0;
s = 0.5*(side1+side2+side3);
Num = s*((s-side1)*(s-side2)*(s-side3));
}
public double getArea(){
return( 1/2*(side1*side2*side3));
}
public double getPerimeter(){
return (side1 + side2 + side3);
}
@Override
public String toString(){
return "Triangle Information:+ “\nside1 = " + side1 + "\nside2 = " + side2 +
"\nside3 = " + side3 + "\ncolor = " + getColor() + "\nfilled =" + isFilled();
}
}
休息
public class DemoTriangle {
public static void main(String[] args) {
Triangle triangle = new Triangle(1, 1.5, 1);
System.out.println(triangle);
triangle.setColor("yellow");
triangle.setFilled(true);
System.out.println("The area is " + triangle.getArea());
System.out.println("The perimeter is " + triangle.getPerimeter());
System.out.println(triangle);
}
}
我正在运行代码,但由于某种原因,它总是将区域返回为“0.0”,而不是三角形的实际区域。我错过了什么?