Java矩形类Y轴倒置问题:坐标计算不符合JUnit测试预期
Let’s break down what’s happening here: your test expects the top-left corner’s Y value to be 20 (10 units above the center’s Y=30) and the bottom-right’s Y to be 40 (10 units below), but your current code is doing the exact opposite.
Root Cause
The Y-axis adjustments in your getTopLeft() and getBottomRight() methods are inverted. Most 2D coordinate systems (like the one your test assumes) treat the top of the screen as lower Y values and the bottom as higher Y values. Your current code moves the top-left point down instead of up, and the bottom-right point up instead of down.
Fixed Rectangle Class
Here’s the corrected version with the Y-axis logic flipped to match your test expectations:
public class Rectangle { public int width = 0; public int height = 0; public Point center; public Rectangle(Point center, int width, int height) { this.width = width; this.height = height; this.center = center; } public Point getTopLeft() { Point point = new Point(center.getX(), center.getY()); // Move left (subtract half width) and up (subtract half height) point.moveRel(-width / 2, -height / 2); return point; } public Point getBottomRight() { Point point = new Point(center.getX(), center.getY()); // Move right (add half width) and down (add half height) point.moveRel(width / 2, height / 2); return point; } public int getWidth() { return width; } public int getHeight() { return height; } }
Quick Verification
With this fix, your testRectangle1() will pass all assertions:
- Top-left X:
20 - 10 = 10✔️ - Top-left Y:
30 - 10 = 20✔️ - Bottom-right X:
20 + 10 = 30✔️ - Bottom-right Y:
30 + 10 = 40✔️
As a side note: For better encapsulation, you might want to make the width, height, and center fields private (like your Point class) and expose them via getters, but that’s optional for your current test case.
内容的提问来源于stack exchange,提问作者user14041112

