Java练习 SDUT-3339_计算长方形的周长和面积(类和对象)
计算长方形的周长和面积(类和对象)
Time Limit: 1000 ms Memory Limit: 65536 KiB
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
习惯性的认为长比宽长,所以在赋值的时候WA了一发。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
String str;
String []s;
Rect a;
while(cin.hasNext())
{
str = cin.nextLine();
s = str.split(" ");
if(s.length==1)
a = new Rect(Integer.parseInt(s[0]));
else
a = new Rect(Integer.parseInt(s[0]),Integer.parseInt(s[1]));
}
cin.close();
}
}
class Rect
{
private int l,w;
Rect(int l,int w)
{
this.l = l;
this.w = w;
if(l<=0||w<=0)
{
this.l = this.w = 0;
}
System.out.println(this.l+" "+this.w+" "+(this.l+this.w)*2+" "+this.l*this.w);
}
Rect(int l)
{
if(l<=0)
this.l = this.w = 0;
else
this.l = this.w = l;
System.out.println(this.l+" "+this.w+" "+(this.l+this.w)*2+" "+this.l*this.w);
}
}
分类:
Java——面向对象
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现