Java-使用在if语句

时间:2016-03-16 18:10:44

标签: java oop

我需要使用我在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);

2 个答案:

答案 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);