该程序假定采用(x,y)坐标以及两个矩形的宽度和高度,并用字符串显示两个矩形,说明它们重叠,包含或不重叠。我有正确的图形。但我的问题在于要显示的字符串的逻辑。当用户为不包含或相互重叠的三角形输入数据时。它说它们重叠。我需要帮助修复代码的逻辑。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Scanner;
public class TwoRectangles extends Application {
public void start(Stage primaryStage) throws Exception {
Pane pane = new Pane();
double width = 400;
double height = 400;
ArrayList<Rectangle> rectangles = new ArrayList<>();
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 2; i++) {
System.out.print("Enter (x, y) of center, width, and height or rec " + i + ": ");
Rectangle temp = new Rectangle(input.nextDouble(), input.nextDouble(), input.nextDouble(),
input.nextDouble());
temp.setFill(Color.TRANSPARENT);
temp.setStroke(Color.BLACK);
rectangles.add(temp);
}
Rectangle rec1 = rectangles.get(0);
Rectangle rec2 = rectangles.get(1);
String s = "";
if (!(rec1.contains(rec2.getWidth(), rec2.getHeight())
|| rec2.contains(rec1.getWidth(), rec1.getHeight()))) {
s = "One rectangle is contained in another.";
} else if (rec1.intersects(rec2.getX(), rec2.getY(), rec2.getWidth(), rec2.getHeight())
|| rec2.intersects(rec1.getX(), rec1.getY(), rec1.getWidth(), rec1.getHeight())) {
s = "One rectangle overlaps another." ;
} else {
s = "The rectangles do not overlap.";
}
Text text = new Text(width * 0.1, height * 0.9, s);
pane.getChildren().add(text);
pane.getChildren().addAll(rectangles);
primaryStage.setTitle("rectangles..");
primaryStage.setScene(new Scene(pane, width, height));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
看起来您的主要问题是您的"包含"检查。 它只考虑矩形的宽度和高度,而不考虑它们的位置。 你可以写一个"包含"方法,比如:
private static boolean contains(Rectangle r1, Rectangle r2) {
return r1.getX() <= r2.getX() && r1.getY() <= r2.getY()
&& r2.getX() + r2.getWidth() <= r1.getX() + r1.getWidth()
&& r2.getY() + r2.getHeight() <= r1.getY() + r1.getHeight();
}
然后将支票更改为
if (contains(rec1, rec2) || contains(rec2, rec1)) {
s = "One rectangle is contained in another.";
} else if (rec1.intersects(rec2.getX(), rec2.getY(), rec2.getWidth(), rec2.getHeight())) {
s = "One rectangle overlaps another.";
} else {
s = "The rectangles do not overlap.";
}
(你只需要单向检查交集,因为如果矩形 A 与 B 相交,那么 B 也与 A 相交)。
嗯,"包含"很简单:
boolean contain = rect1.contains(rect2) || rect2.contains(rect1);
之后,"重叠"很容易:
boolean overlap = ! contain && rect1.intersects(rect2);
或者,要获取字符串,请执行以下操作:
String s = (rect1.contains(rect2) || rect2.contains(rect1)
? "One rectangle is contained in another."
: rect1.intersects(rect2)
? "One rectangle overlaps another."
: "The rectangles do not overlap.");