In: Computer Science
❐Part 1: SingASong Print “Old MacDonald Had a Farm” Lyrics using a function. To the function, you pass the name of animal and the sound as parameters. Document your code carefully. Your program output must be identical to the sample output. OUTPUT OF SAMPLE RUN FOR PART 1 Old MacDonald had a farm Ee i ee i o And on his farm he had some cows Ee i ee i oh With a moo-moo here And a moo-moo there Here a moo, there a moo Everywhere a moo-moo Old MacDonald had a farm Ee i ee i o Old MacDonald had a farm Ee i ee i o And on his farm he had some chicks Ee i ee i o With a cluck-cluck here And a cluck-cluck there Here a cluck, there a cluck Everywhere a cluck-cluck Old MacDonald had a farm Ee i ee i o Old MacDonald had a farm Ee i ee i o And on his farm he had some pigs Ee i ee i o With an oink-oink here And an oink-oink there Here an oink, there an oink Everywhere an oink-oink Old MacDonald had a farm Ee i ee I o
ANSWER :-
GIVEN THAT :-
public class SingASong {
/*Function that takes name of the animal and sound as
parameters and prints lyrics*/
public static void singSong(String name,String sound){
String article; /*used to store the article for this section of the song(a or an)*/
if(sound.equals("oink")){ /*checks if the sound passed is "oink" */
article="an"; /*article is set to "an"*/
}
else{
article="a"; /*article is set to "a"*/
}
/*The following lines print lyrics of the song line by
line*/
System.out.println("Old MacDonald had a farm");
System.out.println("Ee i ee i o");
System.out.println("And on his farm he had some "+name+"s"); /*The name of the animal is used here*/
System.out.println("Ee i ee i
"+(name.equals("cow")?"oh":"o")); /*Prints "Ee i ee i oh" if the
animal is cow, else prints "Ee i ee i o"*/
System.out.println("With "+article+" "+sound+"-"+sound+" here"); /*The sound passed and article is used here*/
System.out.println("And "+article+" "+sound+"-"+sound+" there"); /*The sound passed and article is used here*/
System.out.println("Here "+article+" "+sound+", there "+article+" "+sound); /*The sound passed and article is used here*/
System.out.println("Everywhere "+article+" "+sound+"-"+sound); /*The sound passed and article is used here*/
System.out.println("Old MacDonald had a farm");
System.out.println("Ee i ee i o");
}
public static void main(String[] args){
singSong("cow","moo"); /*calls singSong method by passing cow as animal and moo as sound ,thereby printing the first part of the song*/
singSong("chick","cluck"); /*calls singSong method by passing chick as animal and cluck as sound ,thereby printing the second part of the song*/
singSong("pig","oink"); /*calls singSong method by
passing pig as animal and oink as sound ,thereby printing the third
part of the song*/
}
}
OUTPUT :-