如何在Java类中实现矩形尺寸的输入校验与自动修正

本文介绍如何为java中的`rect`类添加健壮的属性控制逻辑,确保`width`和`length`始终为正整数——对负值自动取绝对值,并通过封装、构造器与setter方法统一管控数据入口。

在面向对象编程中,直接暴露字段(如 public int width;)会破坏封装性,导致外部代码随意赋值,无法保障数据合法性。您当前的 Rect 类中,width 和 length 是包级访问的默认字段,且缺乏初始化约束,因此需重构为私有字段 + 受控访问模式。

首先,将字段设为 private,并提供带校验逻辑的构造器和 setter 方法:

public class Rect {
    private int x;
    private int y;
    private int width;
    private int length;

    // 构造器:强制校验 width 和 length
    public Rect(int x, int y, int width, int length) {
        this.x = x;
        this.y = y;
        this.width = Math.abs(width) == 0 ? 1 : Math.abs(width); // 防0:若绝对值为0,设为1
        this.length = Math.abs(length) == 0 ? 1 : Math.abs(length);
    }

    // 推荐:提供无参构造器,默认尺寸为1×1
    public Rect() {
        this(0, 0, 1, 1);
    }

    // Setter 方法:每次修改都执行校验
    public void setWidth(int width) {
        this.width = Math.abs(width) == 0 ? 1 : Math.abs(width);
    }

    public void setLength(int length) {
        this.length = Math.abs(length) == 0 ? 1 : Math.abs(length);
    }

    // Getter 方法(可选,但符合Java Bean规范)
    public int getWidth() { return width; }
    public int getLength() { return length; }
    public int getX() { return x; }
    public int getY() { return y; }

    public int getPerimeter() {
        return 2 * (width + length);
    }

    public int getArea() {
        return width * length;
    }

    public void move(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void changeSize(int n) {
        if (n == 0) n = 1;
        this.width = Math.abs(n);
        this.length = Math.abs(n);
    }

    public void print() {
        int area = getArea();
        int perimeter = getPerimeter();
        System.out.printf("X: %d%n", this.x);
        System.out.printf("Y: %d%n", this.y);
        System.out.printf("Length: %d%n", this.length); // 注意:原代码中“Length”实际存的是width,此处已按语义修正命名一致性
        System.out.printf("Width: %d%n", this.width);
        System.out.printf("Area: %d%n", area);
        System.out.printf("Perimeter: %d%n", perimeter);
    }

    public static void main(String[] args) {
        // 使用构造器安全创建实例(自动处理负数和零)
        Rect r1 = new Rect(3, 4, -2, -5); // → width=2, length=5
        r1.print();

        // 使用setter动态调整
        r1.setWidth(-10);
        r1.se

tLength(0); // 自动修正为1 System.out.println("\nAfter update:"); r1.print(); } }

关键改进说明:

  • 封装性提升:所有字段私有化,杜绝非法直写;
  • 防御式校验:使用 Math.abs() 消除负号,并额外处理 0 值(矩形边长必须 > 0,故 0 视为无效,强制设为 1);
  • 单一可信入口:所有赋值路径(构造器、setter、changeSize)均经过相同校验逻辑,避免遗漏;
  • 语义清晰化:修正了原代码中 print() 方法里 "Length" 与 "Width" 标签与实际字段的错位(this.width 对应“Width”,this.length 对应“Length”),增强可维护性;
  • 输出优化:printf 中使用 %n 替代 \n,保证跨平台换行兼容性。

⚠️ 注意事项:

  • 若业务要求严格拒绝非正数(而非自动修正),应抛出 IllegalArgumentException,例如:if (width
  • 当前方案是“宽容式修正”,适用于原型开发或用户输入容错场景;生产系统建议结合日志记录或前端提示,明确告知用户输入已被调整。

通过以上重构,Rect 类不仅满足了基础功能需求,更具备了工业级的数据完整性保障能力。