我有一个赋值,要求我创建一个扩展GeometricObject的子类Triangle。我非常接近解决方案,但是我的周边方法存在问题。我遇到的问题是我的程序有时计算正确的周长,有时使用所有3个边的初始1.0值来计算周长。
这是说明: 三角类:您的代码文件夹包含一个名为GeometricObject的类。如果不以任何方式修改此类,请将其扩展为创建名为Triangle的新类。
Triangle类包含:
这是我迄今为止所做的工作(我的代码):
import java.awt.Color;
public class Triangle extends GeometricObject
{
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
//no args constructor.
public Triangle ()
{
}
public Triangle (double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getArea()
{
double s = ( side1 + side2 + side3 ) / 2.0 ;
double area = Math.sqrt ( s * ( s - side1) * (s - side2 ) * (s - side3));
return area;
}
public double getPerimeter()
{
return (side1 + side2 + side3);
}
public Triangle ( double side1 , double side2 , double side3 ,Color color, boolean statement )
{
}
public String toString()
{
return ( "t1.getArea() = " + getArea() + "\nt1.getPerimeter() = " +
getPerimeter() + "\nTriangle: side1 = " +
side1 + ", side2 = " + side2 + ", side3 = " + side3) ;
}
}
这是我从检查测试程序中得到的结果:
这是GeometricObject的代码:
import java.awt.Color;
import java.util.Date;
public class GeometricObject
{
private Color color = Color.WHITE;
private boolean filled;
private Date dateCreated;
/**
* Construct a default geometric object.
*/
public GeometricObject()
{
dateCreated = new Date(); // System time.
}
/**
* Constructs a GeometricObject with a given color and filled state.
* @param color the initial color of the object
* @param filled whether the object is filled
*/
public GeometricObject(Color color, boolean filled)
{
this(); // set the date
this.color = color;
this.filled = filled;
}
/**
* Return current color.
* @return current color.
*/
public Color getColor()
{
return color;
}
/**
* Return true if the object is filled.
* @return true if the object is filled.
*/
public boolean isFilled()
{
return filled;
}
/**
* Set a new filled value.
* @param filled the new filled value.
*/
public void setFilled(boolean filled)
{
this.filled = filled;
}
/**
* Get dateCreated.
* @return the date the object was created.
*/
public Date getDateCreated()
{
return dateCreated;
}
/**
* Return a string representation of this object.
*/
public String toString()
{
return "created on " + dateCreated + "\ncolor: " + color
+ " and filled: " + filled;
}
}
我知道这是一篇很长的帖子,我将非常感谢您的帮助,并提前感谢您的时间和帮助。