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#

Help with my if else code in C#

string input = Console.ReadLine(); int temperature = int.Parse(input); if (temperature < 21 ) { Console.WriteLine( "Too cold! "); } else if (temperature == 21 && temperature == 22) {

Console.WriteLine( "Just right. "); } else if (temperature > 22 ) { Console.WriteLine( "Too hot!"); }

the error says I entered 21 but nothing was printed

2 Answers

Steven Parker
Steven Parker
231,222 Points

:point_right: You have "and" where you probably meant to use "or".

On this line:

  if (temperature == 21 && temperature == 22)

It's not possible for the temperature to be both 21 and 22, so this condition will never be satisfied. You probably meant to combine those equality comparisons with "||" ("or" instead of "and").

The problem is that your boolean is saying "is the temperature 21 and 22?" which will be never true and if the boolean is false then the code inside won't run. The reason it is never true is temperature is one value, so it could either be for example 21 or 22. The "and" operator checks and sees if both conditions are true, and if even one of the conditions are false, then the whole thing is false. Temperature can't ever be 21 and 22 at the same time, so it's always one of the conditions in the "and" condition to be false, which makes everything false. However, if you use the "or" operator, which check and sees if "any" of the conditions are true, then yuor code will work. The "or" operator is similar to the "and" operator, but it checks if any of the conditions are true. If any of them are true, then the whole thing is true. So, you should try using the "or" operator instead of the "and" one.

Here's your condition currently:

temperature == 21 && temperature == 22

Try changing that to:

temperature == 21 || temperate == 22

In your example, you were using "or". in order to fix that, you must you the "or" operator, shown in my example. I hope you understand now :)

Good luck!

Hope this helps, Alex