用java构造函数计算长方形的周长和面积
时间: 2023-05-22 12:04:26 浏览: 72
好的,可以使用以下代码来计算长方形的周长和面积:
```
public class Rectangle {
//长方形的长和宽
double length;
double width;
//构造函数
public Rectangle(double l, double w){
length = l;
width = w;
}
//计算周长
public double getPerimeter(){
return 2 * (length + width);
}
//计算面积
public double getArea(){
return length * width;
}
}
```
使用以下代码来创建对象并调用构造函数:
```
Rectangle r = new Rectangle(4.0, 5.0); //创建一个长为4,宽为5的长方形
System.out.println("周长: " + r.getPerimeter());
System.out.println("面积: " + r.getArea());
```
输出的结果应该为:
```
周长: 18.0
面积: 20.0
```
相关问题
用java 构造函数 写长方形的面积和周长
好的,可以用如下的 Java 构造函数来计算长方形的面积和周长:
```
public class Rectangle {
int length;
int width;
public Rectangle(int l, int w) {
this.length = l;
this.width = w;
}
public int getArea() {
return this.length * this.width;
}
public int getPerimeter() {
return 2 * (this.length + this.width);
}
}
```
在上述代码中,我们定义了一个 Rectangle 类,该类具有两个属性 length 和 width,以及一个构造函数,用于初始化这两个属性值。我们还定义了两个方法 getArea 和 getPerimeter,用于计算长方形的面积和周长。
如果我们创建一个 Rectangle 对象,然后调用 getArea 和 getPerimeter 方法,就可以得到长方形的面积和周长了。例如:
```
Rectangle r = new Rectangle(5, 3);
int area = r.getArea(); // 15
int perimeter = r.getPerimeter(); // 16
```
希望这个问题的答案能够帮到你!
java定义一个长方形类,定义 求周长和面积的方法
好的,以下是定义一个长方形类并定义求周长和面积的方法的 Java 代码:
```
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public double getArea() {
return length * width;
}
}
```
在这个代码中,我们定义了一个 Rectangle 类,它有两个私有属性 length 和 width,分别表示长和宽。我们还定义了一个构造函数,用于初始化这两个属性。接下来,我们定义了两个公共方法 getPerimeter 和 getArea,用于计算长方形的周长和面积。在 getPerimeter 方法中,我们使用了长方形周长的公式 2 * (length + width),在 getArea 方法中,我们使用了长方形面积的公式 length * width。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)