我要解决的问题是编写一个段落,当我说 1
时,我的程序会在歌曲的第二行显示 thumb
。当我的程序显示 2
时,它应该在我歌曲的第二行显示 shoe
。我的程序没有按计划运行,我不确定我是否在 for
循环内正确使用了 switch 语句,或者我的程序顺序是否错误。
import acm.program.*;
public class SingChildSong extends ConsoleProgram {
public void run() {
for (int i = 1; i < 3; i++){
println ("This old man, he played" + i);
switch (i) {
case 1: println("thumb"); break;
case 2: println("shoe"); break;
case 3: println("knee"); break;
}
println ("He played knick-knack on my" + (i));
println ("With a knick-knack, paddy-whack");
println ("Give your dog a bone.");
println ("This old man came rolling home.");
println ( "" );
}
}
}
最佳答案
如果我没猜错,你打算这样做:
...
for (int i = 1; i <= 3; i++){
System.out.println ("This old man, he played " + i);
String word;
switch (i) {
case 1: word = "thumb"; break;
case 2: word = "shoe"; break;
case 3: word = "knee"; break;
}
System.out.println ("He played knick-knack on my " + word);
System.out.println ("With a knick-knack, paddy-whack");
System.out.println ("Give your dog a bone.");
System.out.println ("This old man came rolling home.");
System.out.println ( "" );
}
...
正如您所说,您的书中尚未研究字符串,没有字符串的正确答案应该是:
...
for (int i = 1; i <= 3; i++){
System.out.println ("This old man, he played " + i);
switch (i) {
case 1:
System.out.println ("He played knick-knack on my thumb");
break;
case 2:
System.out.println ("He played knick-knack on my shoe");
break;
case 3:
System.out.println ("He played knick-knack on my knee");
break;
}
System.out.println ("With a knick-knack, paddy-whack");
System.out.println ("Give your dog a bone.");
System.out.println ("This old man came rolling home.");
System.out.println ( "" );
}
...
关于java - 正确使用switch语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14370312/