我需要使用我在if语句中创建的变量。然而,我的代码没有编译。我只需要帮助编译它,同时保持功能相同。
这是代码片段
else if (in.equals("Monster") && in1.equals("Orc"))
{ Players Character = new Orc();
System.out.println("You have chosen "+in+" type "+in1+". Monsters in general are more attack orientated");
}
Character.addAttack(5);
答案 0 :(得分:2)
您必须将声明移到if
:
Players character = null;
// ...
else if (in.equals("Monster") && in1.equals("Orc"))
{
character = new Orc();
System.out.println("You have chosen "+in+" type "+in1+". Monsters in general are more attack orientated");
}
// TODO: check for null
character.addAttack(5);
关于变量范围的一些阅读:http://www.cs.berkeley.edu/~jrs/4/lec/08
答案 1 :(得分:2)
为了使其在if
条件之外工作,您只需要在Character
条件之外宣布if
。
/* Declare it here */
Players Character = null;
if(...) {
/* Do Something Here */
} else if (in.equals("Monster") && in1.equals("Orc")) {
Character = new Orc();
System.out.println("You have chosen " + in + " type " +
in1 + ". Monsters in general are more attack orientated");
}
/* Now you can use it here */
Character.addAttack(5);