這是我的java 作業,啟明星java組,做了一個下午,和大家分享
編寫一個輸出“Ninety-nine Bottles of Beer on the Wall.”歌詞(不知道沒關係,其實我也不知道,不過你認真看下去就會知道)的程式。程式應當以英文的形式列印瓶數,而不是數字。例如:
Ninety-nine bottles of beer on the wall,
Ninety-nine bottles of beer,
Take one down, pass it around,
Ninety-eight bottles of beer on the wall.
...
One bottle of beer on the wall,
One bottle of beer,
Take one down, pass it around,
Zero bottle of beer on the wall.
(bottle的單複數形式不用管它了,當然,能注意到最好)
程式不能使用99個輸出語句!
應為程式設計一個稱為BeerSong的類,它的構造方法取一個整型參數,該參數的初值是牆上的啤酒瓶數。如果該參數小於0,則將瓶數設為0。類似的,如果該參數大於99,則將啤酒瓶數設為99。然後編寫一個稱為PrintSong的共有方法,輸出每一節中的啤酒瓶數,直到0為止。可以添加任何其它有協助的私人方法。
我的答案:
我的答案:
import java.util.Scanner;
public class BeerSong {
static String[] onetotwenty={
" ","one","two","three","four","five","six","seven","eight","nine",
"Ten","Eleven", "twelve ","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen",
"Eighteen","Nineteen","Twenty"
};
static String[] twentytoninety={
"Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"
};
public static void main(String args[]){
//String[] str={"goods","happy"};
System.out.println("請輸入一個數:");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n>99) n=99;
else if(n<0) n=0;
int m=n/10,q=n%10;
if(n>20)
{
for(int i=m-2;i>=0;i--)
{
for(int j=q;j>=0;j--)
{
int a=i,b=j;
if(j==0) q=9;
if(!(i==0&&j==0))
{
System.out.println(twentytoninety[i]+"-"+onetotwenty[j]+" bottles of beer on the wall,");
System.out.println(twentytoninety[i]+"-"+onetotwenty[j]+" bottles of beer, ");
System.out.println("Take one down,pass it around,");
int p=j-1;
if(p<0&&i>0) {i--;p=9;}
System.out.println(twentytoninety[i]+"-"+onetotwenty[p]+" bottles of beer on the wall.");
System.out.println("----------------------------------");
i=a;j=b;
}
}
}
for(int k=19;k>0;k--)
{
System.out.println(onetotwenty[k]+" bottles of beer on the wall,");
System.out.println(onetotwenty[k]+" bottles of beer ,");
System.out.println("Take one down,pass it around,");
if(k>1)
System.out.println(onetotwenty[k-1]+"bottles of beer on the wall.");
else
System.out.println("Zero bottles of beer on the wall.");
System.out.println("----------------------------------");
}
}
else if(n>0&&n<=20)
{
for(int k=n;k>0;k--)
{
System.out.println(onetotwenty[k]+" bottles of beer on the wall,");
System.out.println(onetotwenty[k]+" bottles of beer ,");
System.out.println("Take one down,pass it around,");
if(k>1)
System.out.println(onetotwenty[k-1]+"bottles of beer on the wall.");
else
System.out.println("Zero bottles of beer on the wall.");
System.out.println("----------------------------------");
}
}
else
System.out.println("Zero bottles of beer on the wall.");
}
}