我这里有的是 Java 项目的框架。这是基于创建数据类型,我基本上会让它找到面积、周长,看看它们是否相交或相互包含。我了解我需要使用的公式,但我将如何实际创建矩形 b,就像初始矩形一样,我必须有一个 x、y 中心以及宽度和高度?我曾尝试以类似的方式声明矩形 b,但它拒绝分配任何变量。
为了确定矩形 b 是否与另一个矩形相交,我需要定义它以便计算矩形的角等,这是我的代码:
public class OwnRectangles {
private final double x,y; //center of rectangle
private final double width; //width of rectangle
private final double height; //height of rectangle
public Rectangle(double x0, double y0, double w, double h)
{
x=x0;
y=y0;
width=w;
height=h;
}
public double area()
{
return width*height;
}
public double perimeter()
{
return height*2 + width*2;
}
public boolean intersects(Rectangle b)
{
}
public boolean contains(Rectangle b)
{
}
public void draw(Rectangle b)
{
/*Draw rectangle on standard drawing*/
}
}
我本质上是在尝试创建另一个矩形,我尝试了类似这样的方法,但行不通:
public OwnRectanglesb(double x2, double y2, double w2, double h2)
{
x=x2;
y=y2;
width=w2;
height=h2;
}
不仅这个名称与 OwnRectangles b 不匹配,而且 public... 应该只是 OwnRectangles 如果这有意义的话。非常简单,我想定义第二个要使用的矩形。
最佳答案
OwnRectangle
类需要在您的代码中匹配Rectangle
的使用,例如更改为:
public class Rectangle /* CHANGED FROM OwnRectangle to Rectangle */ {
private final double x,y; //center of rectangle
private final double width; //width of rectangle
private final double height; //height of rectangle
public Rectangle(double x0, double y0, double w, double h)
{
x=x0;
y=y0;
width=w;
height=h;
}
public double area()
{
return width*height;
}
public double perimeter()
{
return height*2 + width*2;
}
public boolean intersects(Rectangle b)
{
}
public boolean contains(Rectangle b)
{
}
public void draw(Rectangle b)
{
/*Draw rectangle on standard drawing*/
}
}
关于java - 在 Java 中创建多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49883597/