Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialArthur Kharzamanov
5,414 PointsWhen do we use member variable and when non-member to call a method?
In the video Craig created a boolean method to apply a guess and then to check for a hit he used this line: boolean isHit = mAnswer.indexOf(letter) >=0;
Why can't we similarly use answer.indexOf(letter) >= 0; ?
In the constructor we set mAnswer = answer, so shouldn't it allow for answer.indexOf(letter) >=0; ?
Here is the whole code:
public class Game { private String mAnswer; private String mHits; private String mMisses;
public Game (String answer) {
mAnswer = answer;
mHits = "";
mMisses = "";
}
public boolean applyGuess(char letter) { boolean isHit = mAnswer.indexOf(letter) >=0; if (isHit) { mHits += letter; } else { mMisses += letter; } return isHit; } }
1 Answer
Corey Johnson
Courses Plus Student 10,192 PointsHello Arthur,
That would not work due to the scope of variables. The answer String variable that is passed to the constructor is only accessible within the constructor method itself. The private class member variables (mAnswer, mHits, and mMisses) are declared at a class level, so they are accessible anywhere in the class itself.
So the value of mAnswer is set to the value of answer when a new Game object is instantiated, via the constructor method. Then any member methods within the class can now access that value (via mAnswer).
I hope this helps. Keep programming!
Arthur Kharzamanov
5,414 PointsArthur Kharzamanov
5,414 PointsYeah, I figured it out when going over the code more thoroughly, but thank you anyway!