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 trialHoessein Abd
Python Web Development Techdegree Graduate 19,107 PointsWhy do we use "-" in this video and not "-=" like we have learned?
In this video we subtract the constant from the amount of misses.
public int getRemainingTries() {
return MAX_MISSES - misses.length();
}
The challenge also denied me to use "-=" it only passes with "-" it gives me a syntax error, so I'm assuming I missed something important.
2 Answers
Steve Hunter
57,712 PointsHi there,
In this example, we just want to evaluate the expression and return the result. So, return MAX_MISSES - misses.length();
evaluates to a number which we return out of the method. At the other end of that, the caller of the method probably assigns that value to something, probably another variable; I don't know.
So, the minus sign does maths and nothing else. It doesn't change any values of variables unless you assign it:
int cakes;
cakes = 5;
// one gets eaten
cakes = cakes - 1;
Here, we evaluate the expression on the right of the =
sign. It evaluates to 4, and we assign that back into cakes
. So, cakes - 1
just creates a number which we assign into cakes
(it could go anywhere) so that cakes
now holds 4.
Shorthand for this is the -=
operator. That deducts and assigns:
int cakes = 5;
cakes -= 1;
This has the same result; cakes
now holds 4. So the -=
operator evaluates and assigns. We don't need to do that in your initial example - we just want to calculate/evaluate the expression and use the number that generates. Indeed, you can't use this as you can't assign into a constant and MAX_MISSES -= misses.length();
doesn't generate a number that can be returned; it is a closed result as the assignment (if it were possible) swallows the evaluation, meaning there's nothing left to return.
I hope that makes sense!
Steve.
Hoessein Abd
Python Web Development Techdegree Graduate 19,107 Pointsaaaah. thanks a lot. I understand :-)
Steve Hunter
57,712 PointsNo problem!