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);
1
  • 7
    You just need to declare Character outside your if. Commented Mar 16, 2016 at 18:11

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

You might also want to link to the naming conventions (since you already fixed his variable name).
Thanks for the link @Tom
@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 feel free to ask a new question for that (maybe stackoverflow.com/questions/2701182/…)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.