BeerSong 这个程序的java 代码

来源:互联网 发布:编程语言执行效率 编辑:程序博客网 时间:2024/04/30 07:34

这是我的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.");

}

}

原创粉丝点击