计算长方形的周长和面积(类和对象java)
2017-03-30 20:34
1631 查看
计算长方形的周长和面积(类和对象)
Time Limit: 1000MS Memory Limit: 65536KBSubmit 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
1 2 3 4 5 2 -2 -2 -3
Example 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
用java写的一个很简单类,用作练手import java.util.*; import java.lang.*; public class Main { private static Scanner in; public static void main(String[] args) { in = new Scanner(System.in); while(true){ String s = in.nextLine(); String[] a = s.split(" "); int b[] = new int [2]; for(int i=0; i<a.length; ++i){ b[i] = Integer.parseInt(a[i]); } if(a.length == 1){ Rect R1 = new Rect(b[0]); System.out.println(R1.getlength() + " " + R1.getwidth() + " " + R1.sslen() + " " + R1.sarea()); } else{ Rect R2 = new Rect(b[0], b[1]); System.out.println(R2.getlength() + " " + R2.getwidth() + " " + R2.sslen() + " " + R2.sarea()); } } } } class Rect{ private int length, width; public Rect(int length){ if(length < 0) this.length = 0; else this.length = length; this.width = this.length; } public Rect(int length, int width){ if(length < 0 || width < 0){ this.length = 0; this.width = 0; return; } this.length = length; this.width = width; } public int sarea(){ if(width == 0) return length * length; return width * length; } public int sslen(){ if(width == 0) return 4 * length; return 2 * (length + width); } public int getlength(){ return length; } public int getwidth(){ return width; } }
相关文章推荐
- java计算长方形的周长和面积(类和对象)
- java_sdut_计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)java sdut ACM 3339
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- Java面向对象深入学习:制作一个画图工具并计算那些图形的面积和周长。
- 用JAVA语言编写程序:包含两个类,一个类Cricle中包含计算圆周长,面积的方法。在另一个类Compute中给出半径值为10,创建对象,并调用Cricle类中的方法,计算该对象的面积、周长并显示出结
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- Java接口实验,计算矩形和圆的周长和面积
- 用JAVA写一个已知半径,计算园周长,面积的程序
- Java计算图形面积周长(4)
- Java计算周长面积,入门
- c++ 计算长方形的周长和面积
- 3-4 计算长方形的周长和面积
- 用get和set取值来计算长方形的周长和面积(包括成员方法和构造方法)