通常,当我听说switch语句时,将它推迟以替换长if ... else链。但是似乎当我使用switch语句时,我正在写更多的代码,而如果...否则我会写。您还遇到其他问题,例如将所有调用的所有变量都保持在同一范围内。
这是一些代表我通常编写的流程的代码(感谢diam)
String comment; // The generated insult.
int which = (int)(Math.random() * 3); // Result is 0, 1, or 2.
if (which == 0) {
comment = "You look so much better than usual.";
} else if (which == 1) {
comment = "Your work is up to its usual standards.";
} else if (which == 2) {
comment = "You're quite competent for so little experience.";
} else {
comment = "Oops -- something is wrong with this code.";
}
然后他们要我用这个替换它:
String comment; // The generated insult.
int which = (int)(Math.random() * 3); // Result is 0, 1, or 2.
switch (which) {
case 0:
comment = "You look so much better than usual.";
break;
case 1:
comment = "Your work is up to its usual standards.";
break;
case 2:
comment = "You're quite competent for so little experience.";
break;
default:
comment = "Oops -- something is wrong with this code.";
}
似乎使用笨拙的语法编写了更多代码。但是使用switch语句真的有好处吗?