【发布时间】:2025-10-23 12:40:02
【问题描述】:
通过选择左手或右手的选项创建“海盗对话”。我希望它对“左”和“右”的不同拼写做出肯定的回答(正如您将在代码中看到的那样),但是,当我为所有不是“右”或“左”的输入添加最终的“其他”代码时,它给了我一个“java.lang.Error”,无法访问的代码。我在添加最终的“else”语句之前测试了我的代码,它按我的意愿工作,再次添加了“else”语句,它给了我同样的错误。
(我也很感激关于如何改进我的代码的提示和反馈,这是我完全自己创建的第二个项目)
不管怎样,代码如下:
package myOwn;
import java.util.Scanner;
public class myArms {
static Scanner sc2 = new Scanner(System.in);
public static void main(String[] args) {
armInput();
}
public static void armInput() {
System.out.println("Behold the arms! Which hand holds the secret item?");
String answer = sc2.nextLine();
System.out.println(armOpener(answer));
}
public static String armOpener(String answer) {
if(answer.equals("left")) {
return "Aha! Indeed the gemstone was hidden in the left hand. Now...";
}else if(answer.equals("Left")) {
return "Aha! Indeed the gemstone was hidden in the left hand. Now...";
}else if(answer.equals("LEFT")) {
return "Aha! Indeed the gemstone was hidden in the left hand. Now...";
}else if(answer.equals("right")) {
return "Bummer! The treasure was in the other hand. Easy for me to say, huh? What if there wasn't a treasure from the start of? Who knows...";
}else if(answer.equals("Right")) {
return "Bummer! The treasure was in the other hand. Easy for me to say, huh? What if there wasn't a treasure from the start of? Who knows...";
}else if(answer.equals("RIGHT")) {
return "Bummer! The treasure was in the other hand. Easy for me to say, huh? What if there wasn't a treasure from the start of? Who knows...";
}else {
return "Did you not hear me boy? I'm asking you, which hand?!";
}
return answer;
}
}
“返回答案”行是以红色下划线结尾的那个。如果我删除最后一个“else”语句,红色下划线就会消失。
【问题讨论】:
-
所以?如果
ifs 都不匹配,您要返回answer,还是要返回"Did you not hear me boy? I'm asking you, which hand?!"。因为现在你的代码试图同时做这两件事。 -
不相关:你可以通过调用
equalsIgnoreCase而不是equals来简化你的代码。 -
红色下划线可能表示类似“无法访问的代码”,因为该语句在返回
if或else块后永远无法执行 -
您的
if else声明是详尽无遗的,因此永远无法到达最后一个return answer;。只需将其删除。 -
顺便说一句,您可以使用
equalsIgnoreCase方法代替equals,进行不区分大小写的比较。这将使您减少if语句的数量。
标签: java if-statement