这是我的代码:
public class Rectangles
{
private final double x;
private final double y;
private final double width;
private final double height;
public Rectangles(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 2*width + 2*height;
}
public boolean intersects(Rectangles b)
{
boolean leftof = ((b.x + b.width)<(x-width));
boolean rightof = ((b.x-b.width)>(x+width));
boolean above = ((b.y-b.height)>(y+height));
boolean below = ((b.y+b.height)<(y-height));
if (leftof==false && rightof==false && above==false && below==false)
return false;
else return true;
}
public void show()
{
StdDraw.setYscale((0),(y+height));
StdDraw.setXscale((0), (x+width));
StdDraw.setPenColor();
StdDraw.rectangle(x,y,.5*width,.5*height);
}
public static void main(String[] args)
{
Rectangles a = new Rectangles(Double.parseDouble(args[0]),
Double.parseDouble(args[1]),
Double.parseDouble(args[2]),
Double.parseDouble(args[3]));
Rectangles b = new Rectangles(0,0,1,1);
System.out.println(a.area());
System.out.println(a.perimeter());
System.out.println(a.intersects(b));
a.show();
b.show();
}
}
我是新手。这是基于创建数据类型的实验室作业。除了System.out.println(a.intersects(b))对于绝对不应该相交的矩形返回true之外,一切都很顺利。更糟糕的是,show()创建的图形显示了它们在绝对不应该相交的情况下相交。例如,(如果我完全错了,请告诉我)%java矩形5 5 3 6肯定不会返回true,对吗?因为以5,5为中心且宽度为3的矩形肯定不会与以0,0为中心且其宽度为1的矩形相交。
感谢您的帮助。我会发布一张显示的图片,但它说我必须有更多的声誉才能发布图片。哦,好吧。它是相交的矩形。
根据一些评论,我编辑了代码,现在看起来像这样:
public class Rectangles
{
private final double x;
private final double y;
private final double width;
private final double height;
public Rectangles(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 2*width + 2*height;
}
public boolean intersects(Rectangles b)
{
boolean intersects = ((b.width / 2) + (width / 2) < Math.abs(b.x - x) &&
(b.height / 2) + (height / 2) < Math.abs(b.y - y));
if (intersects==false)
return false;
else return true;
}
public void show()
{
StdDraw.setYscale((0),(y+height));
StdDraw.setXscale((0), (x+width));
StdDraw.setPenColor();
StdDraw.rectangle(x,y,.5*width,.5*height);
}
public static void main(String[] args)
{
Rectangles a = new Rectangles(Double.parseDouble(args[0]),
Double.parseDouble(args[1]),
Double.parseDouble(args[2]),
Double.parseDouble(args[3]));
Rectangles b = new Rectangles(1.0,1.0,1.0,1.0);
System.out.println(a.area());
System.out.println(a.perimeter());
System.out.println(b.intersects(a));
a.show();
b.show();
}
}
我仍然在得到关于相交的有趣答案,因为某些原因,我的画总是有相交的矩形。我不知道我做错了什么。更改代码后,我尝试了%java矩形5 5 3 6,它说它们相交,并绘制了相交矩形的图像。发生了什么事?