我的初学者类(class)中有一项作业是用 Java 进行编码。这是作业(由我从瑞典语翻译成英语,因此我提前表示抱歉);
CircleList 类跟踪多个圆。实现该类。
指导
- 这个任务不仅应该练习使用 ArrayList,还应该练习用多种方法分解问题。因此,您应该在
add
方法中使用overlaps
方法。 - 为了使方法
overlaps
更容易编写,您应该在overlaps
中使用私有(private)方法circleOverlaps
。 - 如果两个圆的原点之间的距离小于它们的半径之和,则两个圆重叠。
Circle 类看起来像这样;
class Circle {
private double radius;
private double x;
private double y;
/** Constructs a circle with the radie radius and the
center in x, y. */
public Circle(double x, double y, double radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
/** Returns the x coordinate of the center. */
public double getX() {
return x;
}
/** Returns the y coordinate of the center. */
public double getY() {
return y;
}
/** Returns the radius. */
public double radius() {
return radius;
}
/** Returns the area. */
public double area() {
return Math.PI * radius * radius;
}
}
这就是我到目前为止所想出的,(方法已经声明但尚未实现);
public class CircleList {
private ArrayList<Circle> circles;
/** Constructs an empty list for circles. */
public CircleList() {
circles = new ArrayList<Circle>();
}
/** Adds the circle c to the list if it not ovelaps
with any circle in the list. Return true if
circle has been added. */
public boolean add(Circle c) {
circles.add(c);
}
/** Returns true if the circle c ovelaps with any
one circle in this list. */
public boolean overlaps(Circle c) {
}
private boolean circlesOverlaps(Circle c1, Circle c2) {
double r1 = Circle.radius(c1); //radius, x- & y-value of circle 1 (c1)
double x1 = Circle.getX(c1);
double y1 = Circle.getY(c1);
double r2 = Circle.radius(c2); //radius, x- & y-value för circle 2 (c2)
double x2 = Circle.getX(c2);
double y2 = Circle.getY(c2);
double distance = Math.pow((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2), 0.5);
if (r2 >= r1 && distance <= (r2 - r1)){ //c1 is inside c2
}
else if (r1 >= r2 && distance <= (r1 - r2) ) { //c2 is inside c1
}
else if (distance > (r1 + r2)){ //c2 doesn't overlap c1
}
else { //c2 overlaps c1
}
}
}
我真的不知道从哪里开始。而且我现在确实没有人可以问。我知道这是否太多以至于无法开始。不过还是谢谢你。
保重。
最佳答案
基本上,您必须迭代所有圆圈并检查给定的圆圈是否与任何类似的圆圈重叠
public boolean overlaps(Circle c) {
return circles.stream()
.anyMatch(circle -> circlesOverlaps(c, circle));
}
并且您必须从 circlesOverlaps
方法中的 if 条件返回 true
或 false
,具体取决于您是否将一个圆圈视为另一个圆圈是否与您的问题重叠。
您需要更正的另一个地方是
public boolean add(Circle c) {
return circles.add(c);
}
基本上添加 return,因为您需要根据返回类型返回 boolean 值。
关于java - 如果圆 c 与数组列表中的任何其他圆重叠,则返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62001884/