본문 바로가기

개발/Java

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

코드 조각을 한번만 사용하여 아래와 같은 출력 결과를 얻어야 한다.
출력 결과
result 543345
문제
public class Puzzle4 {
	public static void main(String[] args) {
		________________________
		int y = 1;
		int x = 0;
		int result = 0;
		while(x < 6){
			________________
			________________
			y = y * 10;
			________
		}
		x = 6;
		while(x > 0){
			________
			result = result + ____________
		}
		System.out.println("result " + result);
	}
}
	
class ________{
	int ivar;
	________ doStuff(int ____){
		if(ivar > 100){
			return ________
		}
		else{
			return ________
		}
	}
}
코드 조각
ivar = x;
obs.ivar = x;
obs[x].ivar = x;
obs[x].ivar = y;
Puzzle4[] obs = new Puzzle4[6];
Puzzle4[] obs = new Puzzle4[6];
Puzzle4b[] obs = new Puzzle4b[6];
Puzzle4b[] obs = new puzzle4[6];
doStuff(x);
obs.doStuff(x);
obs[x].doStuff(factor);
obs[x].doStuff(x);
ivar
factor
public
private
ivar + factor;
ivar * (2 + factor);
ivar * (5 - factor);
ivar * factor;
x = x + 1;
x = x - 1;
Puzzle4
Puzzle4b
Puzzle4b()
int
short
obs[x] = new Puzzle4b(x);
obs[] = new Puzzle4b();
obs[x] = new Puzzle4b();
obs = new Puzzle4();
정답
public class Puzzle4 {
	public static void main(String[] args) {
		Puzzle4b[] obs = new Puzzle4b[6];
		int y = 1;
		int x = 0;
		int result = 0;
		while(x < 6){
			obs[x] = new Puzzle4b();
			obs[x].ivar = y;
			y = y * 10;
			x = x + 1;
		}
		x = 6;
		while(x > 0){
			x = x - 1;
			result = result + obs[x].doStuff(x);
		}
		System.out.println("result " + result);
	}
}
	
class Puzzle4b{
	int ivar;
	public int doStuff(int factor){
		if(ivar > 100){
			return ivar * factor;
		}
		else{
			return ivar * (5 - factor);
		}
	}
}