Java矩形类面积/周长输出0

问题描述 投票:0回答:2

当我运行Rectangle.java时,我可以在Rectangle中获得输入的长度和宽度,但是当我尝试使用吸气剂计算面积/周长时,得到的结果为零

我试图添加和删除setter,将其放入getArea和getPerimeter中的getter / setter方法中,但是似乎没有任何作用

//Code provided by the teacher as a template 
Rectangle temp = new Rectangle();
        temp.print();
        System.out.println();

        temp.setLength(2.5);
        temp.setWidth(3.0);
        //Consider how your rectangle will change after setting the length and width to specific values.
        temp.print();

        System.out.println();

        Rectangle r = new Rectangle(3.5,2);
        r.print();




//My Class

public class Rectangle 
{
    private static double length;
    private static double width;
    private static double perimeter;
    private static double area;

    public Rectangle(double length, double width)
    {
        setLength(length);
        setWidth(width);
    }

    public Rectangle()
    {

    }

    public static double getLength() 
    {
        return length;
    }
    public static void setLength(double length) 
    {
        Rectangle.length = length;
    }
    public static double getWidth() 
    {
        return width;
    }
    public static void setWidth(double width)
    {
        Rectangle.width = width;
    }   
    public static double getPerimeter(double length, double width) 
    {
        return 2*width+2*length;
    }

    public static double getArea(double length, double width) 
    {
        area= getLength()*getWidth();
        return length*width;
    }


    public static String print() 
    {
        String Rectangle = new String();
        System.out.println("This rectangle has a length of "+length+" and a width of "+width);
        System.out.println("The area of the rectangle is: "+ area);
        System.out.println("The perimeter of the rectangle is: "+ perimeter);
        return Rectangle;

    }
}

没有错误消息。

输出:

此矩形的长度为0.0,宽度为0.0矩形的面积是:0.0矩形的周长为:0.0

此矩形的长度为2.5,宽度为3.0矩形的面积是:0.0矩形的周长为:0.0

此矩形的长度为3.5,宽度为2.0矩形的面积是:0.0矩形的周长为:0.0

java getter-setter
2个回答
0
投票

请不要在var上使用static关键字。因为静态var只能通过静态方法进行操作。如果要使用带有static关键字的var,请将static添加到setter方法。


0
投票

您需要更改打印方法并调用周长和面积方法,以使这些变量获得所需的值

© www.soinside.com 2019 - 2024. All rights reserved.