7-99 设计一个矩形类Rectangle分数 10
设计一个名为Rectangle的类表示矩形。这个类包括:
- 两个名为width和height的double类型数据域,它们分别表示矩形的宽和高。width和height的默认值都为1。
- 一个用于创建默认矩形的无参构造方法。
- 一个创建指定width和height值的矩形的构造方法。
- 一个名为getArea()的方法,返回该矩形的面积。
- 一个名为getPerimeter()的方法,返回周长。
编写一个测试程序,分别输入两个矩形的高和宽,创建两个Rectangle对象。按照顺序显示每个矩形的宽、高、面积和周长。
输入格式:
在一行内输入4个数据,依次为两个矩形的高和宽
输出格式:
每行输出一个矩形的宽、高、面积和周长,中间用空格隔开
输入样例:
在这里给出一组输入。例如:
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;
//本体采用了两种方法,一种用toString稍稍改进了一下,少打一行,但数量越多越明显
class Rectangle7_99{
private double width = 1;
private double height = 1;
Rectangle7_99() {
width = 1;
height = 1;
}
Rectangle7_99(double width,double height){
this.width = width;
this.height = height;
}
double getArea() {
return width*height;
}
double getPerimeter() {
return 2*(width+height);
}
public String toString() {
return this.width+" "+this.height+getArea()+" "+getPerimeter();
}
}
public class Pta_7_99 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double w1 = sc.nextDouble();
double h1 = sc.nextDouble();
double w2 = sc.nextDouble();
double h2 = sc.nextDouble();
Rectangle7_99 r1 = new Rectangle7_99(w1,h1);
Rectangle7_99 r2 = new Rectangle7_99(w2,h2);
//System.out.println(w1+" "+h1+" "+r1.getArea()+" "+r1.getPerimeter());
//System.out.println(w2+" "+h2+" "+r2.getArea()+" "+r2.getPerimeter());
System.out.println(r1);
System.out.println(r2);
}
}