본문 바로가기

개발/Java

[Head First Java] Chapter3 연습문제 수영장 퍼즐

코드 조각을 한번만 사용하여 아래와 같은 출력 결과를 얻어야 한다.
출력 결과
triangle 0, area = 4.0
triangle 1, area = 10.0
triangle 2, area = 18.0
triangle 3, area = 28.0
y = 4, t5 area = 343.0
코드 조각
x
y
area
ta.area
ta.x.area
ta[x].area
Triangel[] ta = new Triangle(4);
Triangle ta = new[] Triange[4];
Triangle[] ta = new Triangle[4];
4, t5 area = 18.0
4, t5 area = 343.0
27, t5 area = 18.0
27, t5 area = 343.0
ta[x] = setArea();
ta.x = setArea();
ta[x].setArea();
int x;
int y;
int x = 0;
int x = 1;
int y = x;
28.0
30.0
x = x + 1;
x = x + 2;
x = x - 1;
ta.x
ta(x)
ta[x]
x < 4
x < 5
ta = new Triangle();
ta[x] = new Triangle();
tz.x = new Triangle();
문제
class Triangle {
	double area;
	int height;
	int length;
	
	public static void main(String[] args){
		________________
		________________________________
		while(_____){
			________________________________
			_____.height = (x + 1) * 2;
			_____.length = x + 4;
			________________________________
			System.out.print("triangle " + x + ", area");
			System.out.println(" = " + ____.area);
			________________
		}
		________________
		x = 27;
		Triangle t5 = ta[2];
		ta[2].area = 343;
		System.out.print("y = " + y);
		System.out.println(", t5 area = " + t5.area);
	}

	void setArea(){
		____ = (height * length) / 2;
	}
}
정답
class Triangle {
	double area;
	int height;
	int length;
	
	public static void main(String[] args){
		int x = 0;
		Triangle[] ta = new Triangle[4];
		while(x < 4){
			ta[x] = new Triangle();
			ta[x].height = (x + 1) * 2;
			ta[x].length = x + 4;
			ta[x].setArea();
			System.out.print("triangle " + x + ", area");
			System.out.println(" = " + ta[x].area);
			x = x + 1;
		}
		int y = x;
		x = 27;
		Triangle t5 = ta[2];
		ta[2].area = 343;
		System.out.print("y = " + y);
		System.out.println(", t5 area = " + t5.area);
	}

	void setArea(){
		area = (height * length) / 2;
	}
}