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

Problem Description

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

Input

Output

Sample Input
1
2 3
4 5
2
-2
-2 -3
Sample 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

package pp;

import java.util.*;

class Rect {
private int length;
private int width;

public Rect(int length) {
if(length < 0) {
length = 0;
}
this.length = length;
this.width = length;// 正方形宽==长
}

public Rect(int length, int width) {

if(length < 0 || width < 0) {
length = 0;
width = 0;
}

this.length = length;
this.width = width;
}

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

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

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

}

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
Rect rect = null;
String s = sc.nextLine();
String[] array = s.split(" ");

if (array.length == 1) {
int length = Integer.parseInt(array[0]);
rect = new Rect(length);
} else if (array.length == 2) {
int length = Integer.parseInt(array[0]);
int width = Integer.parseInt(array[1]);
rect = new Rect(length, width);
}
System.out.println(rect.toString());
}

sc.close();
}
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120