# 计算长方形的周长和面积（类和对象）

### 计算长方形的周长和面积（类和对象）

Time Limit: 1000MS Memory Limit: 65536KB

#### Problem Description

（1）Rect(int length) —— 1个整数表示正方形的边长
（2）Rect(int length, int width)——2个整数分别表示长方形长和宽

输入多组数据；

#### Output

每行测试数据对应一行输出，格式为：(数据之间有1个空格）

#### Example Input

1
2 3
4 5
2
-2
-2 -3

#### Example Output

1 1 4 1
2 3 10 6
4 5 18 20
2 2 8 4
0 0 0 0
0 0 0 0

#### Author

zhouxq

 
import java.util.*;

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
Rect rect;
String strData = sc.nextLine();
String[] arrayData = strData.split(" ");// 分隔符
int count = arrayData.length;
if (count == 1) {
int length = Integer.parseInt(arrayData[0]);
rect = new Rect(length);
} else {
int length = Integer.parseInt(arrayData[0]);
int width = Integer.parseInt(arrayData[1]);
rect = new Rect(length, width);
}
System.out.println(rect.toString());
}
sc.close();
}
}

class Rect {
private int length;
private int width;

public Rect(int length) {
this(length, length);
}

public Rect(int length, int width) {
if (length < 0)
length = 0;
if (width < 0)
width = 0;
this.width = width;
this.length = length;
}

public int length() {
return 2 * (length + width);
}

public int area() {
return length * width;
}

public String toString() {
String result = length + " " + width + " " + length() + " " + area();// 控制输出格式
return result;
}

}