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 trialEvan Welch
1,815 PointsCorrect use of Ternary if statement
Are these two if statements equivalent? My code is not checking correctly. If askes me if I included the Boolean expression. I think I have included the boolean expression (value < 0). Any help would be appriciated!
int value = -1;
string textColor = null;
if (value < 0)
{
textColor = "red";
}
else
{
textColor = "green";
}
(value < 0) ? textColor = "red" : textColor = "green";
5 Answers
Evan Welch
1,815 Pointsvalue = -1;
string textColor = value < 0 ? "red" : "green";
This answer worked! Thank you Reggie Williams!
Evan Welch
1,815 PointsThank you Reggie Williams.
But, even when I compile my code as follows I do not pass the quiz.
int value = -1;
string textColor = null;
value < 0 ? textColor = "red" : textColor = "green";
Thanks again.
Reggie Williams
Treehouse TeacherHey Evan Welch that's a bit closer but instead of writing textColor more than once you can assign the value of the ternary operation to textColor
textColor = condition goes here ? "option if true" : "option if false";
Evan Welch
1,815 PointsOk, I think I see what you mean. So I would write:
int value = -1;
string textColor = value < 0 ? "red" : "green";
Right?
Michael Musch
966 PointsWhy doesn't this challenge accept the exact formatting we were just taught?
(value < 0) ? textColor = "red" : textColor = "green";
Reggie Williams
Treehouse TeacherMichael Musch be sure to start a new thread when you have a question so it doesn't get lost but this challenge is asking you to initialize the value variable so you'll want to use the above format that acts as a single variable definition. The example you provided also requires writing textColor twice which goes against the concept of D.R.Y or don't repeat yourself
Reggie Williams
Treehouse TeacherReggie Williams
Treehouse TeacherEvan Welch you can shorten this code by assigning the result to textcolor that way you don't have to repeat anything and the result is stored in the variable
variable = condition < 0 ? "value1" : "value2";