[Head First Java] "맥주 99병"

2011. 6. 1. 15:06

Head First Java 41페이지 맥주 99병 관련 문제

원본 소스
public class BeerSong {
	public static void main(String[] args){
		int beerNum = 99;
		String word = "bottles";
		
		while(beerNum > 0){
			if(beerNum == 1){
				word = "bottle";	
			}
			
			System.out.println(beerNum + " " + word + " of beer on the wall");
			System.out.println(beerNum + " " + word + " of beer.");
			System.out.println("Take one down.");
			System.out.println("pass it around.");
			beerNum = beerNum - 1;
			
			if(beerNum > 0){
				System.out.println(beerNum + " " + word + " of beer on the wall");
			}
			else{
				System.out.println("No more bottles of beer on the wall");				
			}
		}
	}
}


결과물
99 bottles of beer on the wall
99 bottles of beer.
Take one down.
pass it around.
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer.
Take one down.
pass it around.
.
.
.
1 bottles of beer on the wall
1 bottle of beer on the wall
1 bottle of beer.
Take one down.
pass it around.
No more bottles of beer on the wall
위와 같이 98병 째에서 bottles of beer on the wall 문장이 두번이 나온다.
그리고 마지막 1병째에서 bottles 라고 표시한다.

책에서도 흠이 있다고 확인해보라고 한다.

수정한 소스
			//if(beerNum > 0){
			//	System.out.println(beerNum + " " + word + " of beer on the wall");
			//}
			if(beerNum < 1){
				System.out.println("No more bottles of beer on the wall");				
			}

수정된 소스의 결과물
99 bottles of beer on the wall
99 bottles of beer.
Take one down.
pass it around.
98 bottles of beer on the wall
98 bottles of beer.
Take one down.
pass it around.
.
.
.
1 bottle of beer on the wall
1 bottle of beer.
Take one down.
pass it around.
No more bottles of beer on the wall
7~22줄 내용을 수정하여 상황에 맞게 표시 되도록 수정함

Binple 개발/Java , ,