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

hafizul islam rusho
hafizul islam rusho
2,269 Points

help with C# if/else challenge

i might be miss understanding the challenge.

The following table describes my room temperature preferences. Print the message from the table when a user enters a number in the corresponding range. For example, if temperature is 21 the code should print "Just right." to the screen. Temperature (°C) Message Less than 21° Too cold! 21° to 22° Just right. Greater than 22° Too hot!

CodeChallenge.cs
string input = Console.ReadLine();
int temperature = int.Parse(input);

if (temperature < 21) {
    System.Console.Write("Too cold!"); }
else (temperture = 21) {
   System.Console.Write("Just right."); } 
else if (temperture > 22){
    System.Console.Write("Too hot!"); }

4 Answers

Steven Parker
Steven Parker
231,269 Points

I think you have the right idea, but a few errors. Here's some hints:

  • an else statement takes no conditional expression
  • an "else if" cannot follow a plain else
  • you spelled "temperture" (missing an "a") in two places
  • you have an assignment operator ("=") where you probably want a comparison ("==")
  • check your conditions, what happens when the temperature is exactly 22?

And a suggestion: if you handle the "too hot" and "too cold" cases first, a plain else could cover everything else.

hafizul islam rusho
hafizul islam rusho
2,269 Points

how do i put 21 & 22 in else?

string input = Console.ReadLine(); int temperature = int.Parse(input);

if (temperature < 21) { System.Console.Write("Too cold!"); } else if (temperature > 22) { System.Console.Write("Too hot!"); } else (temperature == 21) { System.Console.Write("Just right."); }

Steven Parker
Steven Parker
231,269 Points

Remember, a plain else takes no conditional expression.

It doesn't need one since it handles all conditions not already covered by the previous if and else if statements.

string input = Console.ReadLine(); int temperature = int.Parse(input);

if(temperature < 21) { Console.WriteLine("Too Cold!"); } else if(temperature ==21) { Console.WriteLine("Just right."); } else if(temperature == 22) { Console.WriteLine("Just right."); } else { Console.WriteLine("Too hot!"); }

Justin Molyneaux
Justin Molyneaux
13,329 Points

Steven Parker's got you covered!