您的位置:首页 > 其它

计算长方形的周长和面积(类和对象)

2017-03-27 20:31 288 查看



计算长方形的周长和面积(类和对象)

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic


Problem Description

设计一个长方形类Rect,计算长方形的周长与面积。
成员变量:整型、私有的数据成员length(长)、width(宽);
构造方法如下:
(1)Rect(int length) —— 1个整数表示正方形的边长
(2)Rect(int length, int width)——2个整数分别表示长方形长和宽
成员方法:包含求面积和周长。(可适当添加其他方法)
要求:编写主函数,对Rect类进行测试,输出每个长方形的长、宽、周长和面积。


Input

 输入多组数据;
一行中若有1个整数,表示正方形的边长;
一行中若有2个整数(中间用空格间隔),表示长方形的长度、宽度。
若输入数据中有负数,则不表示任何图形,长、宽均为0。


Output

 每行测试数据对应一行输出,格式为:(数据之间有1个空格)
长度 宽度 周长 面积


Example Input

12 34 5-22-2 -3


Example Output

1 1 4 12 3 10 64 5 18 202 2 8 40 0 0 00 0 0 0

import java.util.Scanner;
interface Shape{
abstract int lengt();
abstract int area();
}
class Triangle implements Shape{
Triangle(int a1){
if(a1 <= 0){
a = 0;
}
else a =a1;
}
int a;
public int lengt(){
if(a <= 0){
a = 0;
return 0;}
else return 4*a;
}
public int area(){
if(a <= 0){
a = 0;
return 0;}
else return a*a;
}
}

class Re implements Shape{
Re(int x1,int y1){
if(x1 <=0 || y1 <= 0){
x1 = 0;
y1 = 0;
}
else {
x = x1;
y = y1;}
}
int x,y;
public int lengt(){
if(x <= 0 || y <= 0){
x = 0;
y = 0;
return 0;}
else
return (x+y)*2;
}
public int area(){
if(x <= 0 || y <= 0){
x = 0; y = 0;
return 0;}
else return x * y;
}
}
public class Main {
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
String str;
while(reader.hasNext()){
str = reader.nextLine();
String[] temp = str.split(" ");
int[] result = new int[temp.length];
for(int i = 0; i < temp.length; i++){
result[i] = Integer.valueOf(temp[i]);
}
int k = 0;
for(int i = 0; i < result.length; i++){
k++;
}
if(k == 1){
Triangle t = new Triangle(result[0]);
System.out.println(t.a+" "+t.a+" "+t.lengt()+" "+t.area());
}
else if(k == 2){
Re r = new Re(result[0],result[1]);
System.out.println(r.x+" "+r.y+" "+r.lengt()+" "+r.area());
}
}
}
}
import java.util.Scanner;
class re{
int l;
int w;
re(int l){
if(l <= 0)
l = 0;
else
this.l = l;
}
re(int l,int w){
if(l <= 0 || w <= 0){
l = 0;
w = 0;
}
else {
this.l = l;
this.w = w;
}
}
int getlength(){
if(l <= 0)
return 0;
else return 4*l;
}
int getarea(){
if(l <= 0)
return 0;
else return l*l;
}
int getl(){
if(l <= 0 || w <= 0)
return 0;
else return l+l+w+w;

}
int geta(){
if(l <= 0 || w <= 0)
return 0;
else return l*w;
}
}
public class Main {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);
while(reader.hasNext()){
String s = reader.nextLine();
String a[] = s.split(" ");
int b = a.length;
if(b == 1){
int c = Integer.parseInt(a[0]);
re r = new re(c);
System.out.println(r.l+" "+r.l+" "+r.getlength()+" "+r.getarea());
}
else{
int c = Integer.parseInt(a[0]);
int d = Integer.parseInt(a[1]);
re r = new re(c,d);
System.out.println(r.l+" "+r.w+" "+r.getl()+" "+r.geta());
}
}
}
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: