我在学校遇到这个问题,对此我感到很困惑

问题描述 投票:-8回答:1

这是我分配给学校的问题之一,这非常令人困惑。我什至不知道从哪里开始。

方向:在提供的空白处,编写下面描述的Rectangle类。

实例变量:

  • 矩形的宽度和高度的双变量(3分)

构造函数:

  • 将宽度和高度初始化为0(2 pts)的默认构造函数
  • 第二个构造函数,它接受宽度和高度的值。
  • 宽度应该是第一个参数,高度应该是第二个参数。 (2分)

示例] new Rectangle(2.5,7)

方法:

  • 为每个实例变量创建变量和访问器(4分)
  • double perimeter()–返回矩形的周长为double(3 pts)
  • double area()–返回矩形的面积为double(3 pts)
  • toString()–必须调用perimeter方法。返回以下形式的字符串:(3 pts)20

矩形:宽度= 2.5,高度= 7,周长= 19

java
1个回答
0
投票

这将是我的解决方案。请务必阅读内联注释。

public class Rectangle {
    private double width, height; //declare the instance variables

    public Rectangle() {
        width = 0; //set both instance variables to zero
        height = 0;
    }

    public Rectangle(double width, double height) {
        this.width = width; //set the instance variables to the passed-in variables
        this.height = height;
    }

    public double getWidth() {
        return width; //accessor for width
    }

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

    public double getHeight() {
        return height; //accessor for height
    }

    public void setHeight(double height) {
        this.height = height; //mutator for height
    }

    public double perimeter() {
        return (width + height) * 2; //perimeter = 2 widths and w heights
    }

    public double area() {
        return width * height; //area = width * height
    }

    @Override
    public String toString() {
        return "Rectangle: Width = " + width + ", Height = " + height
                + ", Perimeter = " + perimeter(); //construct a string with all the required parameters
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.