Rectangle类
public class Rectangle {
private float width;
private float height;
public float perimeter() {
// 求周长
return (width + height) * 2;
}
public float area() {
// 求面积
return width * height;
}
public void price(){
System.out.println("草皮的总价为:"+String.format("%.2f",area()*12)+"元");
}
public void setRectangle(float width, float height) {
//有参构成,输入参数放到对象里
this.height = height;
this.width = width;
}
public void defaultRectangle() {
//无参构造,设置默认值,调用方法
this.height = 2;
this.width = 1;
System.out.println("r1的周长为:"+String.format("%.2f",perimeter())+"米");
perimeter();
}
}
主方法
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("草皮的长和宽,中间用空格分隔:");
float width = sc.nextFloat();
float height = sc.nextFloat();
Rectangle r2 = new Rectangle();
//把参数放入到对象里
r2.setRectangle(width, height);
//计算地皮价格
r2.price();
//ri周长独立计算
Rectangle r1 = new Rectangle();
r1.defaultRectangle();
}
}
计算结果
草皮的长和宽,中间用空格分隔:
5 6
草皮的总价为:360.00元
r1的周长为:6.00米