You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Java Rectangle类计算面积/周长返回0的问题求助

问题根源:静态成员(static)的误用 + 未正确计算面积/周长

你遇到的问题核心有两个:所有成员变量和方法都被错误地标记为static,以及**print()方法没有主动计算面积和周长,而是直接使用未初始化的成员变量**。咱们一步步拆解解决:

1. 为什么static是问题?

static修饰的变量和方法属于类本身,而不是类的实例对象。也就是说,你创建的所有Rectangle对象都会共享同一个lengthwidthareaperimeter值——这显然不符合矩形对象的设计逻辑(每个矩形应该有自己的长和宽)。更关键的是,你的print()方法直接读取的是从未更新过的areaperimeter静态变量,自然一直输出0。

2. 修复步骤

第一步:移除不必要的static修饰符

把类里所有的static都删掉:成员变量(lengthwidth)不需要static,所有的getter/setter、getArea()getPerimeter()print()方法也不需要static。另外,areaperimeter完全不需要作为成员变量存储——它们可以通过长和宽实时计算,没必要占内存。

第二步:修正getArea和getPerimeter方法

这两个方法不需要传入参数,直接使用当前对象的lengthwidth计算即可:

  • getArea():返回length * width
  • getPerimeter():返回2 * (length + width)

第三步:修正print()方法

让它调用getArea()getPerimeter()来获取实时计算的结果,而不是读取未更新的成员变量。

修改后的完整Rectangle类代码

public class Rectangle {
    // 去掉static,每个对象有自己的长和宽
    private double length;
    private double width;

    // 带参构造方法:初始化长和宽
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // 无参构造方法:默认长和宽为0
    public Rectangle() {
        this.length = 0;
        this.width = 0;
    }

    // getter和setter:去掉static,操作当前对象的属性
    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    // 计算周长:不需要参数,直接用当前对象的长和宽
    public double getPerimeter() {
        return 2 * (length + width);
    }

    // 计算面积:不需要参数,直接用当前对象的长和宽
    public double getArea() {
        return length * width;
    }

    // 打印方法:调用getter和计算方法获取实时值
    public void print() {
        System.out.println("This rectangle has a length of " + getLength() + " and a width of " + getWidth());
        System.out.println("The area of the rectangle is: " + getArea());
        System.out.println("The perimeter of the rectangle is: " + getPerimeter());
    }
}

验证效果

现在运行教师提供的测试代码:

Rectangle temp = new Rectangle();
temp.print();
System.out.println();
temp.setLength(2.5);
temp.setWidth(3.0);
temp.print();
System.out.println();
Rectangle r = new Rectangle(3.5,2);
r.print();

输出会变成:

This rectangle has a length of 0.0 and a width of 0.0
The area of the rectangle is: 0.0
The perimeter of the rectangle is: 0.0

This rectangle has a length of 2.5 and a width of 3.0
The area of the rectangle is: 7.5
The perimeter of the rectangle is: 11.0

This rectangle has a length of 3.5 and a width of 2.0
The area of the rectangle is: 7.0
The perimeter of the rectangle is: 11.0

完美解决你的问题!

内容的提问来源于stack exchange,提问作者Hlib Tarabrov

火山引擎 最新活动