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

Time Limit: 1000 ms Memory Limit: 65536 KiB

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个空格)

长度 宽度 周长 面积

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

Hint

 

Source

zhouxq

 

 

import java.util.Scanner;
import java.util.*;
import java.lang.*;

class Rect{
    int length;
    int width;
    public int length(){
        if(this.length<0||this.width<0)
        {
            return 0;
        }
        else {
            return this.length;
        }
    }
    public int width(){
        if(this.length<0||this.width<0)
        {
            return 0;
        }
        else if(this.length!=0&&this.width==0)
        {
            return this.length;
        }
        else {
            return this.width;
        }
    }
    public int zhouchang() {
        if(this.length<0||this.width<0)
        {
            return 0;
        }
        if(this.length!=0&&this.width==0)
        {
            return this.length*4;
        }
        else if(this.length!=0&&this.width!=0)
        {
            return this.length*2+this.width*2;
        }
        return 0;
    }
    public int area() {
        if((this.length<0||this.width<0))
        {
            return 0;
        }
        if(this.length!=0&&this.width==0)
        {
            return this.length*this.length;
        }
        else if(this.length!=0&&this.width!=0)
        {
            return this.length*this.width;
        }
        return 0;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int a, b;
        while(reader.hasNext())
        {
            Rect r = new Rect();
            String str = reader.nextLine();
            String s[] = str.split(" ");
            if(s.length==1)//计算划分后字符串数组的长度,若只有一个数则给长赋值,若有两个数给长和宽赋值
            {
                r.length = Integer.parseInt(s[0]);
                r.width = 0;
            }
            else if(s.length==2)
            {
                r.length = Integer.parseInt(s[0]);
                r.width = Integer.parseInt(s[1]);
            }
            int l, w, z;
            l = r.length();
            w = r.width();
            z = r.zhouchang();
            a = r.area();
            System.out.printf("%d %d %d %d\n", l,w,z,a);
        }
    }
}

你可能感兴趣的:(Java--计算长方形的周长和面积(类和对象)