I have a question about weather it’s legal to use a switch statement inside a for loop. The way its written below Eclipse gives me an error and won’t let me use switch(n) on the second statement in the for loop. What I want to do is write…
This old man, he played 1
He played knick-knack on my thumb.
Is there a better way of solving the problem below with a for loop and switch statement? I want to write out the paragraphs 10 different with the different number and different case. So 1 thumb, 2 shoe, 3 knee…. until 10.
import acm.program.*;
public class SingSong extends ConsoleProgram {
public void run() {
for (int n = 1; n <= 10; n++) {
println("This old man, he played " + n);
println("He played knick-knack on my" + switch(n));
println("With a knick-knack, paddy-whack,");
println("Give your dog a bone");
println("This old man came rolling home");
switch (n) {
case 1 : println("thumb"); break;
case 2 : println("shoe"); break;
case 3 : println("knee"); break;
case 4 : println("door"); break;
case 5 : println("hive"); break;
case 6 : println("sticks"); break;
case 7 : println("heaven"); break;
case 8 : println ("pate"); break;
case 9 : println("spine"); break;
case 10 : println("shin"); break;
}
}
}
}
What you want is a method you’ll call:
Then replace
with
Another, more succint approach would be to create an array of strings:
and then just use