1

I need to use a variable I created inside an if statement. My code however, doesn't compile. I just need assistance in compiling it while keeping the functionality the same.

Here is a fragment of the code

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);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
duldi
  • 180
  • 1
  • 17

2 Answers2

2

You have to move the declaration outside the 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);

Some reading about variables scope: http://www.cs.berkeley.edu/~jrs/4/lec/08

  • 1
    You might also want to link to the [naming conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html) (since you already fixed his variable name). – Tom Mar 16 '16 at 18:16
  • 1
    Thanks for the link @Tom –  Mar 16 '16 at 18:16
  • @RC. If I could call on your services once more, I cant call methods that are in any subclasses of Players. Would you know why? – duldi Mar 23 '16 at 22:25
  • @duldi feel free to ask a new question for that (maybe http://stackoverflow.com/questions/2701182/call-a-method-of-subclass-in-java) –  Mar 24 '16 at 06:10
2

In order to make it work outside your if condition you just need to declare the Character outside your if condition.

/* 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);
user2004685
  • 9,548
  • 5
  • 37
  • 54