我的代码不会在 catch 块处终止,也不会返回“ERROR”,即使我提供了以下情况 输入永远不会匹配“歌曲”、“笑话”或“故事”。并且总是返回给我聊天机器人的名字。有什么原因吗???
String execute(String command) {
String result = "";
try{
switch(command) {
case "song":
result += " sings: Like a Rolling Stone ...";
break;
case "joke":
result += " says: Why are Communists bad Java programmers?They dont't like classes.";
break;
case "story":
result += " says: A long long time ago ...";
break;
}
} catch (InputMismatchException e) {
return "ERROR";
}
return this.ChatBotName + result;
}
答案 0 :(得分:1)
原因是代码正在运行,并且不会抛出任何可以捕获的错误。 switch 语句中没有匹配的分支不是错误。您可以从 here
查看有关 switch 语句的更多详细信息答案 1 :(得分:0)
除了使用 try 和 catch 块,您还可以不使用 switch case 中的 default case。
String execute(String command) {
String result = "";
switch(command) {
case "song":
result += " sings: Like a Rolling Stone ...";
break;
case "joke":
result += " says: Why are Communists bad Java programmers?They dont't like classes.";
break;
case "story":
result += " says: A long long time ago ...";
break;
default:
return "ERROR";
break;
}
return this.ChatBotName + result;
}