You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java矩形类Y轴倒置问题:坐标计算不符合JUnit测试预期

Fixing Y-Coordinate Swap Between TopLeft and BottomRight in Rectangle Class

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:42:55