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

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

import java.util.*;

public class Main {
	public static void main(String args[]) {
		Scanner reader = new Scanner(System.in);
		while (reader.hasNext()) {
			String s = reader.nextLine();
			String ch[]=s.split(" ");
			if (ch.length == 1) {
				int length =Integer.parseInt(ch[0]);
				if(length<=0)
				{
					System.out.println("0 0 0 0");
				}
				else
				{
					Rect Rect = new Rect(length);
				    int Long=Rect.length();
				    int size=Rect.area();
				    System.out.printf("%d %d %d %d\n",length,length,Long,size);
				}
				
			}
			else {
				int length=Integer.parseInt(ch[0]);
				int width=Integer.parseInt(ch[1]);
				if(length<=0||width<=0)
				{
					System.out.println("0 0 0 0");
				}
				else
				{
				Rect Rect = new Rect(length, width);
				int Long=Rect.length();
				int size=Rect.area();
				System.out.printf("%d %d %d %d\n",length,width,Long,size);
				}
			}

		}
		reader.close();
	}
}

class Rect {
	int length;
	int width;
	Rect(int length)
	{
			this.length = length;
		    this.width = length;
	}

	Rect(int length, int width)
	{
			this.length = length;
			this.width = width;
	}

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

	int area() {
		return length * width;
	}


}

开始时我用的字符数组,会导致如果是负数,负号不能紧跟着数字,而是单独存放,所以不能用tocharArray();

import java.util.Scanner;
public class Main
{
	public static void main(String args[])
	{
		Scanner reader=new Scanner(System.in);
		while(reader.hasNext())
		{
			String s=reader.nextLine();
			String ch[]=s.split(" ");
			int length=0;
			int area=0;
			if(ch.length==1)
			{
			int h=Integer.parseInt(ch[0]);
			if(h<0)
			{
				System.out.printf("0 0 0 0\n");
			}
			else
			{
				length=2*(h+h);
				area=h*h;
				System.out.println(h+" "+h+" "+length+" "+area);
			}
			}
			else if(ch.length==2)
			{
				int h=Integer.parseInt(ch[0]);
				int w=Integer.parseInt(ch[1]);
				if(h<0||w<0)
				{
					System.out.printf("0 0 0 0\n");
				}
				else
				{
					length=2*(h+w);
					area=h*w;
					System.out.println(h+" "+w+" "+length+" "+area);
				}
			}
		}}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奈何桥上的幽灵野草

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值