public static String hero() {
Scanner scanner = new Scanner(System.in);
System.out.println("Which hero will you play as: Wizard, Elf or Dwarf?");
heroType = scanner.nextLine();
if (heroType.equalsIgnoreCase("wizard") || heroType.equalsIgnoreCase("elf") || heroType.equalsIgnoreCase("dwarf")){
//code
return heroType;
}
else {
System.out.println("This character is not recognised, please choose from Wizard, Elf or Dwarf.");
hero();
}
}
我希望此方法仅在选择了3个选项之一时返回heroType,否则应再次调用该方法。但这会产生编译器错误,因为if语句之外没有return语句。最后使用return语句的问题是main方法有一个" String h = hero();"而且" h"传递给其他方法,但如果用户首先选择向导精灵或矮人之外的其他东西,那么自己纠正它们," h"第一次仍然存储扫描仪的原始错误值。
它应该按照我的想法工作,因为用户最终必须提供正确的值(因为该方法只是再次调用)并且最终会有返回值,但它不会。
答案 0 :(得分:3)
使用:
return hero();
而不只是调用hero();
答案 1 :(得分:0)
我不喜欢递归方法。 保持简单和可扩展。
public class Test
{
private static final Set<String> HEROES = new HashSet<>(4);
static {
HEROES.add("wizard");
HEROES.add("elf");
HEROES.add("dwarf");
}
public static final void main(final String... args) {
hero();
}
public static final String hero() {
final Scanner scanner = new Scanner(System.in);
String heroType;
while (true) {
System.out.println("Which hero will you play as: Wizard, Elf or Dwarf?");
heroType = scanner.nextLine().trim().toLowerCase();
if (HEROES.contains(heroType)) {
return heroType;
}
System.out.println("This character is not recognised, please choose from Wizard, Elf or Dwarf.");
}
}
}