본문 바로가기

Java/본격 Java 퀴즈 기초

[Java] 사각형 넓이과 둘레 구하기(클래스 이용)

앞 쪽에 했었던 원의 넓이 구하는 방법과 비슷하게 코딩하였다.

.

.

package ex3;

class Rectangle{
	private float length = 1.0f;
	private float width = 1.0f;
	
	Rectangle(){}
	
	Rectangle(float length, float width){
		this.length = length;
		this.width = width;
	}
	
	public float getLength(){ return length; }
	public void setLength(float length) { this.length = length;}
	public float getWidth(){ return width; }
	public void setWidth(float width) { this.width = width; }
	
	public double getArea() { return length * width; }
	public double getPerimether() { return (length + width) * 2;}
	
	public String toString() {
		return "Rectangle[ lenght = " + length + ", width = " + width + " ]";
	}
}
public class TestRectangle {

	public static void main(String[] args) {
		Rectangle rec1 = new Rectangle();
		Rectangle rec2 = new Rectangle(5.0f, 3.5f);
		
		System.out.println(rec1);
		System.out.println("Area = " + rec1.getArea());
		System.out.println("Perimeter = " + rec1.getPerimether());
		
		System.out.println("");
		
		System.out.println(rec2);
		System.out.println("Area = " + rec2.getArea());
		System.out.println("Perimeter = " + rec2.getPerimether());
	}

}
728x90
반응형