JAVA题目~矩形类Rectangle Exp03-1

  • Post author:
  • Post category:java


【问题描述】定义一个矩形类Rectangle,为其设置私有成员变量length(长)和width(宽)。自动生成两个参数的构造方法,用两个参数分别初始化两个成员变量;添加一个参数的构造方法,将矩形当作正方形,用一个参数初始化两个成员变量;添加无参构造方法,无参构造方法的方法体为空。

为Rectangle类的两个成员,自动生成公有的get方法和set方法,并为两个set方法添加简单的控制逻辑:企图将成员变量设为负值时,输出提示信息并退出程序。

在TestRectangle类的main()方法中创建长和宽分别为len和wid的矩形r1,边长为side的正方形r2,边长未知的矩形r3(长和宽为默认值)。上述len,wid和side的值均从键盘输入。

先输出三个矩形的周长,然后将r3的长和宽修改为和r1相同,再次输出r3的周长。输入输出格式如样例所示,其中:红色文字为真正的程序输入,蓝色文字为输入提示。

【样例输入1】

3 4

5

【样例输出1】


Please enter the length and width of rectangle r1:



3 4



Please enter the side length of square r2:



5


The perimeter of r1 is 14.0

The perimeter of r2 is 20.0

The perimeter of r3 is 0.0

After modification, the perimeter of r3 is 14.0

import java.util.Scanner;

 class Rectangle {

	private double length, width;

	public Rectangle(double length, double width) {
		super();
		this.length = length;
		this.width = width;
	}

	public Rectangle(double side) {
		super();
		this.length = side;
		this.width = side;
	}

	public Rectangle() {
	}

	public double getLength() {
		return length;
	}

	public void setLength(double length) {
		if(length<0)
			{
			System.out.printf("Error!");
			System.exit(-1);
			}
		this.length=length;

	}

	public double getWidth() {
		return width;
	}

	public void setWidth(double width) {
		if(width<0)
		{
		System.out.printf("Error!");
		System.exit(-1);
		}
		this.width = width;
	}
	double getPeri()
	{
		return 2*(length+width);
	}
}
public class TestRectangle
{
	public static void main(String[] args)
	{
	Scanner sc=new Scanner(System.in);
	System.out.printf("Please enter the length and width of rectangle r1:\n");
	double len=sc.nextDouble();
	double wid=sc.nextDouble();
	System.out.printf("Please enter the side length of square r2:\n");
	 double side=sc.nextDouble();
	 Rectangle r1=new  Rectangle(len,wid);
	 Rectangle r2=new  Rectangle(side);
	 
	 Rectangle r3=new  Rectangle();
	 System.out.println("The perimeter of r1 is "+r1.getPeri());
	 System.out.println("The perimeter of r2 is "+r2.getPeri());
	 System.out.println("The perimeter of r3 is "+r3.getPeri());
	 r3.setLength(r1.getLength());
	 r3.setWidth(r1.getWidth());
	 System.out.println("After modification, the perimeter of r3 is "+r3.getPeri());
	sc.close();
	}
}



版权声明:本文为qq_39953607原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。