计算长方形的周长和面积(类和对象)(SDUT 3339)
2023-06-13 09:17:22 时间
说明:主要是练习类和对象的定义,用于笔试。
计算长方形的周长和面积(类和对象)
Problem Description
设计一个长方形类Rect,计算长方形的周长与面积。
成员变量:整型、私有的数据成员length(长)、width(宽);
构造方法如下:
(1)Rect(int length) —— 1个整数表示正方形的边长
(2)Rect(int length, int width)——2个整数分别表示长方形长和宽
成员方法:包含求面积和周长。(可适当添加其他方法)
要求:编写主函数,对Rect类进行测试,输出每个长方形的长、宽、周长和面积。
public class Main {
public static void main(String[] args){
}
}
class Rect{
private int length,width;
Rect(int length){ // 构造方法
this.length = length;
}
Rect(int length, int width){
this.length = length;
this.width = width;
}
int getLength(){ //方法
return length;
}
int getWidth(){
return width;
}
int getArea(){
return length * width;
}
int getCirc(){
return (length + width) * 2;
}
}
类就是这么定义的,就完成任务了吧。
但是根据题目的不同,再完善类的构造方法与方法。
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 sc = new Scanner(System.in);
while(sc.hasNext()){
Rect re; // 声明对象
String str = sc.nextLine(); //读入
String []s = str.split(" "); //分割
int len = s.length; // 判断有几个数
if(len == 1){
int x = Integer.parseInt(s[0]); // 用这个方法来弄一下QAQ
re = new Rect(x);
}
else {
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
re = new Rect(x,y);
}
System.out.println(re.toStr());
}
}
}
class Rect{
private int length,width;
public Rect(int length){ // 构造方法
this (length, length);
}
public Rect(int length, int width){
if(length < 0) this.length = 0;
if(width < 0) this.width = 0;
this.length = length;
this.width = width;
}
public int getLength(){ //方法
return length;
}
public int getWidth(){
return width;
}
public int getArea(){
return length * width;
}
public int getCirc(){
return (length + width) * 2;
}
// 自己定义一个输出,不定义也没事,再输出的时候自己处理一下
public String toStr(){
String res = length + " " + width + " " + getCirc() + " " + getArea() ;
return res;
}
}
相关文章
- Vue3中计算属性的Setter
- golang如何计算两个日期之间的日期差?
- 【新书推荐】《计算化学中的密度矩阵重正化群方法》
- 【强烈推荐,讲座分享】IEEE计算智能学会演化调度与组合优化Taskforce系列讲座第7期:学习优化车辆路径规划问题
- SQLServer 错误 2519 由于无法初始化内部的表达式计算器,从而无法检查对象 ID O_ID(对象 “O_NAME”)的计算列和用户定义类型。 故障 处理 修复 支持远程
- TIC2018 趣谈 | 区块链、人工智能大热 云计算竟是落地推手
- 达内Linux云计算让技术之路更加简单(达内linux云计算培训)
- MSSQL让精准的经纬度计算变得轻松(经纬度计算mssql)
- MySQL:智能化精准计算技术(mysql 计算)
- 利用 Oracle 进行行项计算的技术实践(oracle中行项计算)
- Oracle中月初日期计算函数活用(oracle中月初函数)
- 2B2C两手抓,雾链要借雾计算打造区块链开放生态丨TokenShow
- javascript计算星座属相(十二生肖属相)示例代码
- C++计算ICMP头的校验和实例
- PHP计算一年多少个星期和每周的开始和结束日期
- 计算一个Java对象占用字节数的方法