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 trialKane Watts
8,217 PointsHelp. Can I get help with the boolean expression?
In the previous video, we saw how a ternary if statement could be used in place of an if/else statement to determine the value to return from a method. Ternary if statements can also be used to determine the value to use when initializing a variable. Use a ternary if statement instead of an if/else statement to initialize the textColor variable to the string value "red" if the value variable is less than "0", otherwise initialize the textColor variable to the string value "green".
int value = -1;
string textColor = null;
if (value < 0)
{
textColor = "red";
}
else
{
textColor = "green";
}
5 Answers
Jon Wood
9,884 PointsSo it's asking you to change the if/else
statement into a ternary statement. What you should do is something like this:
string textColor = {boolean expression} ? {what to return if true} : {what to return if false}
Hope that helps, but let me know if you need more details.
Jesse Richards
13,964 Pointsreturn textColor = (value < 0) ? textColor = "red" : textColor = "green"; why is this not working?
Jesse Richards
13,964 PointsNevermind I got it.
Krystal Welch
1,067 PointsWhat did you do? I'm getting an error saying : Bummer! Did you include the "red" and "green" string literal expressions (separated by a colon) to the right of the ternary operator?
using : return textColor = (value < 0) ? textColor = "red":textColor = "green";
Steven Parker
231,269 PointsYou can't use return except in a function, you don't need it here. And don't try to assign inside the ternary expression, just put the possible values there. Take another look at Jon's example of how to format it.
Krystal Welch
1,067 PointsThanks. I got it
Steven Parker
231,269 PointsThe "boolean expression" is the same one in the if statement.
Jon's given you a good generic example of the ternary itself, but it seemed like you were asking specifically about the boolean expression used in the ternary? That's just the same as the boolean expression used in the if statement in the original code.
Steven Parker
231,269 PointsCongratulations to Jesse and Krystal on resolving your issue!
tafadzwa manzunzu
3,601 Pointstafadzwa manzunzu
3,601 Pointsi did what you said but its still giving me a bummer int value = -1; string textColor = null; string textColor = {value < 0} ? {textColor = "red"} : {textColor = "green"} help