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 trial

C# C# Basics (Retired) Perfect if / else if / else

Pratham Patel
Pratham Patel
4,976 Points

I keep getting an error saying i entered 22 i expected just right but got too hot instead

What did i do wrong

CodeChallenge.cs
string input = Console.ReadLine();
int temperature = int.Parse(input);
if (temperature < 21)
{
    System.Console.WriteLine("Too cold!");
}
else if (temperature == 21)
{
    System.Console.WriteLine("Just right.");
}
else 
{
    System.Console.WriteLine("Too hot!");
}

3 Answers

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

Your one if statement is wrong. It should be this way:

else if (temperature == 21 || temperature == 22)

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Cindy Lea is correct. However, you could shorten the amount you type in the else if condition by using this line:

else if (temperature < 23)

Anything less than 21 will get "Too cold!". Anything less than 23 but 21 or greater (ie 21 and 22) will get "Just right!". Anything else will get "Too hot!". Remember that when a condition is evaluated to true it stops the if else and will not be evaluated further.

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,858 Points

Hey there Rakesh,

You code is completely correct syntactically, but it's just not what the challenge is looking for. You coded it based on the example given (of a "just right temp" of 21); however, it's the little chart below the question that the conditionals need to match up with.

So, the DRYest way would to just change the condition in the else if to <= 22. Even though this will check for everything that is equal to or less than 22, the code will only execute if the temperature is 21 or 22, because of the if statement above. If the temperature is less than 21, the if block will execute and the else if won't even be looked at. Make sense?

You could use or in a compound conditional, but this way (in my opinion) is just cleaner code.

Keep Coding! :)

else if (temperature <= 22)

:dizzy: