PDA

View Full Version : Need help with switch structure/repetition (JavaScript)



jcquint
16 Jul 2010, 01:15 PM
Hi guys, college student here having some trouble with the JavaScript portion of my computer science class. I'm almost done with this week's assignment, but this one problem is giving me fits.

It asks me to wite a script that uses repetition and a switch structure to print the song 'The Twelve Days of Christmas.'

I somewhat understand what it is trying to get me to do... something along the lines of, case "1": A partridge in a pear tree. case "2": case "1" + two turtle doves...

And I also know that I should probably make a variable for each "day".. I just can't wrap my head around the problem as a whole. Please help me. I'm not some lazy student on here begging yall to do my homework, I just can't get help from my professor since the class is being taken in and online format and can't afford a tutor! I've worked hard on this and hate to hit this wall.

Thanks in advance guys...

<CrGeary.com/>
16 Jul 2010, 04:06 PM
Well its difficult to show you how you could do it, without actually doing it for you. I would do it something like this, although i would use an array of phrases from each of the 12 days of the song. And i would calculate the length of it rather than hand coding etc..

Basically, if you created a for() loop, ( as you want it repetitive ),obviously you have 12 days of Christmas, so you want to repeat it 12 times. Each day, 1 - 2 - 3 - 4 - 5 - 6 ... etc.. You would have a switch statement do detect the day and add the appropriate phrase, like this:


var curday = 12;
var song = '';

for( curday = 2; curday > 0; curday-- ){
switch( curday ){
case 1:
song += 'A partridge in a pear tree' + '<br/>';
break;
case 2:
song += 'Two Turtle Doves' + '<br/>';
break;
}
}
document.write( song );