JAVA实现矩形(长方形)的周长面积计算

1.首先,我们定义一个矩形类
矩形的类:
a.成员变量:长,宽;
b.成员方法:求周长:(长+宽)*2; 求面积:长

class Rectangle {
	//长方形的长
	private int length;
	//长方形的宽
	private int width;
	
	public Rectangle(){}
	
	//这里只提供setXxx(),因为getXxx()在这暂时不用
	public void setLength(int length) {
		this.length = length;
	}
	
	public void setWidth(int width) {
		this.width = width;
	}
	
	//求周长
	public int getZhouChang() {
		return (length + width) * 2;
	}
	
	//求面积
	public int getArea() {
		return length * width;
	}
}

测试类,计算周长和面积并打印

class RectangleTest {
	public static void main(String[] args) {
		//创建键盘录入对象
		Scanner sc = new Scanner(System.in);
		
		System.out.println("请输入长方形的长:");
		int length = sc.nextInt();
		System.out.println("请输入长方形的宽:");
		int width = sc.nextInt();
		
		//创建对象
		Rectangle jx = new Rectangle();
		//先给成员变量赋值
		jx.setLength(length);
		jx.setWidth(width);
		
		System.out.println("周长是:"+jx.getZhouChang());
		System.out.println("面积是:"+jx.getArea());
	}
}

运行如下:
JAVA实现矩形(长方形)的周长面积计算_第1张图片

你可能感兴趣的:(JAVA_SE)