计算长方形的周长和面积(类和对象)
2017-04-17 19:28
369 查看
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
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); while(in.hasNext()){ Rect rect; String data = in.nextLine(); String []arraydata = data.split(" "); int count = arraydata.length; if(count == 1){ int length = Integer.parseInt(arraydata[0]); rect = new Rect(length); }else{ int length = Integer.parseInt(arraydata[0]); int width = Integer.parseInt(arraydata[1]); rect = new Rect(length,width); } System.out.println(rect.toString()); } } } class Rect{ private int length; private int width; public Rect(int length){ this(length , length);//作为方法名来初始化对象 } public Rect(int length,int width){ if(length < 0) length = 0; if(width < 0) width = 0; this.length = length; this.width = width; } public int girth(){ return 2*(length + width); } public int area(){ return length*width; } public String toString(){ String result = length + " " + width+ " " + girth() + " " + area(); return result; } }
相关文章推荐
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- java计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)java sdut ACM 3339
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象java)
- java_sdut_计算长方形的周长和面积(类和对象)
- 计算长方形的周长和面积(类和对象)
- 3-4 计算长方形的周长和面积
- 3-4 计算长方形的周长和面积--SDUT
- 3-4 计算长方形的周长和面积
- 定义圆类Circle,数据成员有半径radius,成员函数有默认构造函数(默认半径为10)、构造函数、计算圆面积、圆周长以及输出函数,分别构造默认对象和半径为15的对象,输出各对象的周长与面积。
- 3-4 计算长方形的周长和面积
- 3-4 计算长方形的周长和面积
- sdut 3-4 计算长方形的周长和面积
- C语言程序初体验-第四课-第一题:计算长方形的周长和面积
- 计算长方形或正方形的周长和面积