Java编程关于LOOP

来源:百度知道 编辑:UC知道 时间:2024/05/25 09:12:54
菜鸟求助!
初学者,自己有琢磨了一下!
但是也不是很懂!
希望高手帮忙下面的编程
/**
* Print out all verses of the song "n Green Bottles" for a given start
* value n. All verses are the same except for the count of the number of
* bottles (and the number minus 1). The output in the case of n == 3 should be:
他这里说是要我们Method nGreenBottles,
假如 n==3, 那么要求print out 下面这样的几句!

3 green bottles hanging on the wall
3 green bottles hanging on the wall
And if 1 green bottle should accidentally fall
There'll be 2 green bottles hanging on the wall

2 green bottles hanging on the wall
2 green bottles hanging on the wall
And if 1 green bottle should accidentally fall
There'll be 1 green bottle hanging on the wall

1 green bottle hanging on the wall
1 green bottle hanging on the wall
And if 1 green bottle should accidentally fall
There'll be no green bottles hanging on the wall

--------------

简单的问题,用messageFormat解决时最合理的,虽然可能不符合老师的要求。
import java.text.* ;
MessageFormat form = new MessageFormat (
"{0} green {0,choice,1#bottle|1<boottles} hanging on the wall \r\n" +
"{0} green {0,choice,1#bottle|1<boottles} hanging on the wall \r\n" +
"And if 1 green bottle should accidentally fall \r\n" +
"There'll be {1,choice,0#no|0<{1}} green {1,choice,0#bottle|1#bottle|1<bottles}hanging on the wall \r\n" ) ;

for (int i = numberOfBottles; i > 0 ; i --)
{
System.out.println (form.format (new Object [] {new Integer (i), new Integer (i - 1)})) ;
}

注意其中使用了choice format格式串。