public class Rectangle{
private double width;
private double height;
public double area(){
return width*height;
}
public double perimeter(){
return (width+height)*2;
}
public Rectangle(){}
public Rectangle(double width,double height){
this.width=width;
this.height=height;
}
public void setWidth(double width){
this.width=width;
}
public double getWidth(){
return width;
}
public double setHeight(double height){
this.height=height;
}
public double getHeight(){
return height;
}
}
public class Test{
public static void main(String... args){
Rectangle a = new Rectangle();
a.setWidth(width);//此处width填入你所需要的宽度
a.setHeight(height);//此处height填入你所需要的高度
Rectangle b = new Rectangle(width,height);//此处width与height分别填入你所需要的宽度与高度
System.out.println(a.area());//a的面积
System.out.println(a.perimeter());//a的周长
System.out.println(b.area());//b的面积
System.out.println(b.perimeter());//b的周长
}
}
类Rectangle:
public class Rectangle {
private double width;
private double height;
public Rectangle(){
}
public Rectangle(double width , double height){
this.width = width;
this.height = height;
}
public double area(){
return width * height;
}
public double perimeter(){
return 2 * (width + height);
}
// getter and setter
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
类Test:
public static void main(String[] args) {
Rectangle recOne = new Rectangle();
recOne.setWidth(200);
recOne.setHeight(100);
System.out.println("第一种方法计算周长和面积");
System.out.println("周长:" + recOne.perimeter());
System.out.println("面积:" + recOne.area());
Rectangle recTwo = new Rectangle(200 , 100);
System.out.println("第二种方法计算周长和面积");
System.out.println("周长:" + recTwo.perimeter());
System.out.println("面积:" + recTwo.area());
}
Text 类:
public class Text {
public static void main(String[] args) {
Rectangle a=new Rectangle();
a.setWidth(2);
a.setHeight(3);
Rectangle b=new Rectangle(3,4);
System.out.println("面积:"+a.area()+" 周长"+a.perimeter());
System.out.println("面积:"+b.area()+" 周长"+b.perimeter());
}
}
Rectangle类:
private int width;
private int height;
public Rectangle(){
}
public Rectangle(int width,int height){
this.width=width;
this.height=height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int area(){
return this.width*this.height;
}
public int perimeter(){
return (this.width+this.height)*2;
}