创建“海盗对话”,并选择左手或右手。我希望它对“ left”和“ right”的不同拼写给出肯定的答案(正如您将在代码中看到的那样),但是,当我为不是“ right”或“ left”的所有输入添加最终的“ else”代码时,它给了我一个“ 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”语句,红色下划线消失了。