PTA(类与对象)用java写 7-13 设计一个矩形类Rectangle

设计一个名为Rectangle的类表示矩形。这个类包括:

两个名为width和height的double类型数据域,它们分别表示矩形的宽和高。width和height的默认值都为1。
一个用于创建默认矩形的无参构造方法。
一个创建指定width和height值的矩形的构造方法。
一个名为getArea()的方法,返回该矩形的面积。
一个名为getPerimeter()的方法,返回周长。
编写一个测试程序,分别输入两个矩形的高和宽,创建两个Rectangle对象。按照顺序显示每个矩形的宽、高、面积和周长。

输入格式:

输出格式:
每行输出一个矩形的宽、高、面积和周长,中间用空格隔开

输入样例:
在这里给出一组输入。例如:

4 40 3.5 35.9
输出样例:
在这里给出相应的输出。例如:

4.0 40.0 160.0 88.0
3.5 35.9 125.64999999999999 78.8

在这里插入代码片
import java.util.Scanner;
class Rectangle{
	double width,height,area,perimeter;

    Rectangle(){
        width=1;
        height=1;
    }
Rectangle(double width,double height){
    this.width=width;
    this.height=height;
}
public double getArea(){
    area=width*height;
    return area;
}

public double getPerimeter(){
    perimeter=2*(width+height);
    return perimeter;
}
}

public class Main{
    public static void main(String []args){
     Scanner sc=new Scanner(System.in);
       double width1=sc.nextDouble();
        double height1=sc.nextDouble();
        double width2=sc.nextDouble();
        double height2=sc.nextDouble();
        Rectangle s1=new Rectangle( width1,height1);
        Rectangle  s2=new Rectangle( width2,height2);
        System.out.println(width1+" "+height1+" "+s1.getArea()+" "+s1.getPerimeter());
        System.out.println(width2+" "+height2+" "+s2.getArea()+" "+s2.getPerimeter());
    }
}
  

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐