Search code examples
c#if-statementswitch-statementconsole.writeline

C# Switch Case with if statements not returning me the console.WriteLines


I am trying to create a simple switch case with If-Statements code.

Problem:

I don't get any value back.

For Example:

If I put int Temperature = 0; the Code should output "Es ist kalt". But my console doesn't display anything.

using System;

namespace SwitchCase
{
    class Program
    {
        static void Main(string[] args)
        {
            int Temperatur = 25;

            switch (Temperatur)
     
            {
                    case 1:
                    if (Temperatur <= 0)
                    {
                        Console.WriteLine("Es ist kalt");
                    }
                    break;
                    case 2:
                    if (Temperatur >= 25)
                    {
                        Console.WriteLine("Es ist überdurchschnittlich warm");
                    }
                    break;
                    case 3:
                    if (Temperatur <= 13)
                    {
                        Console.WriteLine("Es ist mild");
                    }
                    break;
                    
                


            };

        }
    }
}

Solution

  • your if block never reaches a situation where temperature is 0.

    you only have cases for temperatures 1, 2 and 3 (case 1:), so if temperature is anything else than those, nothing will happen.

    Therefore, you should use if/else statements:

    if (Temperatur <= 0)
    {
        Console.WriteLine("Es ist kalt");
    }
    else if (Temperatur <= 13)
    {
        Console.WriteLine("Es ist mild");
    }
    else
    {
        Console.WriteLine("Es ist überdurchschnittlich warm");
    }