编程实现矩形类,其中包括计算矩形周长和面积的方法,并测试方法的正确性,用JAVA编写

2024-11-07 01:50:28
推荐回答(2个)
回答1:

/**
* 矩形类
*/
public class Rectangle {
private double length; //长
private double width; //宽

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 Rectangle() {
}

public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

/**
* 面积计算方法
* @param length 长
* @param width 宽
* @return 面积
*/
public double area(){
return length*width;
}

/**
* 周长计算方法
* @param length 长
* @param width 宽
* @return 周长
*/
public double girth(){
return 2*(length+width);
}

public static void main(String[] args) {
//定义矩形,长为4.5,宽为3
Rectangle rectangle=new Rectangle(4.5,3);

System.out.println("矩形面积是:"+rectangle.area());
System.out.println("矩形周长是:"+rectangle.girth());
}
}

回答2:

public class juzhen {

public static double mianji(double chang,double kuan) {
ruturn chang*kuan;
}
public static double zhouchang(double chang,double kuan) {
ruturn 2*(chang+kuan);
}
}