自定义类-矩形(Rectangle Class)

为了方便,一个source文件中包括了实体类和测试类两个类。

麻雀虽小,五脏俱全,慢慢的体会到OOP的博大精深了。


代码如下:

package example;
//JHTP Exercise 8.4: Rectangle Class
//by [email protected]
/**(Rectangle Class) Create a class Rectangle with attributes length and 
 * width, each of which defaults to 1. Provide methods that calculate the
 *  rectangle’s perimeter and area. It has set and get methods for both 
 *  length and width. The set methods should verify that length and width 
 *  are each floating-point numbers larger than 0.0 and less than 20.0. 
 *  Write a program to test class Rectangle.
*/
import java.util.Scanner;

class Rectangle {
	private double length=1;
	private double width=1;
	
	public double getLength(){	
		return this.length;	
	}
	public double getWidth(){	
		return this.width;	
	}
	
	public void setLength(double length){	
		if (length<0.0 || length>20.0){
			throw new IllegalArgumentException ("长度不在正确范围内!");
		}
		this.length=length;
	}
	public void setWidth(double width){
		if (length<0.0 || length>20.0){
			throw new IllegalArgumentException ("宽度不在正确范围内!");
		}
		this.width=width;	
	}
	
	public	double calcPerimeter(){
		return 2*(this.length+this.width);
	}
	
	public	double calcArea(){
		return this.length*this.width;
		}
}


public class RectangleTest {

	public static void main(String[] args) {

		Scanner input=new Scanner(System.in);
		Rectangle r1=new Rectangle();
		Rectangle r2=new Rectangle();
		Rectangle r3=new Rectangle();
		double length=0;
		double width=0;
		
		r1.setLength(2.5);
		r1.setWidth(3.5);
		r2.setLength(16.5);
		r2.setWidth(19.8);
		
		System.out.printf("预定义矩形1长度:%.2f,宽度:%.2f\n",r1.getLength(),r1.getWidth());
		System.out.printf("预定义矩形1周长:%.2f,面积:%.2f\n\n",r1.calcPerimeter(),r1.calcArea());
		System.out.printf("预定义矩形2长度为:%.2f,宽度为:%.2f\n",r2.getLength(),r2.getWidth());
		System.out.printf("预定义矩形2周长:%.2f,面积:%.2f\n\n",r2.calcPerimeter(),r2.calcArea());
		
		System.out.printf("请输入自定义矩形的长和宽:");
		length=input.nextDouble();
		width=input.nextDouble();
		r3.setLength(length);
		r3.setWidth(width);
		System.out.printf("自定义矩形3长度为:%.2f,宽度为:%.2f\n",r3.getLength(),r3.getWidth());
		System.out.printf("自定义矩形3周长:%.2f,面积:%.2f\n\n",r3.calcPerimeter(),r3.calcArea());
		
		}		
}

你可能感兴趣的:(Java编程(Java,Programming))