简体   繁体   中英

How can i fix my beginner if and else code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyFirstTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 value = 57;

            if (value < 10)

                Console.WriteLine("Value is less than 10");

            else (value = 57)

                Console.WriteLine("Value is 57!");

            else

                Console.WriteLine("Value is greater than 10");


            Console.ReadLine();
        }
    }
}

I am a complete beginner and have just started learning C#. I have tried to create a snippet of code using the if and else statements.

When it gets to the below, it throws me some squiggly lines and expects { } .

else (value = 57) 
Console.WriteLine("Value is 57!");`

How can i go about fixing this? An explanation would also be great to help a beginner! Thank you in advance.

namespace MyFirstTest
{
   class Program
   {
       static void Main(string[] args)
       {
           Int32 value = 57;

           if (value < 10)
           {
               Console.WriteLine("Value is less than 10");
           }
           else if(value == 57)
           {
               Console.WriteLine("Value is 57!");
           }
           else
           {
               Console.WriteLine("Value is greater than 10");
           }

           Console.ReadLine();
       }
   }
}

Firstly you are using if...else if...else Statement, rather than using else for the second time, you have to use else if as you are checking like if the first condition is true, if not true then else if, second condition is true then at last we use else, if any of the above mentioned conditions are not true. Secondly, to compare, we use == not =

So here your code goes like

if(value < 10)
{ 
    Console.WriteLine("Value is less than 10");
}
else if(value == 57)
{ 
    Console.WriteLine("Value is 57!");
}
else
{ 
    Console.WriteLine("Value is greater than 10");
}

For more information see control statements at https://www.tutorialspoint.com/csharp/if_else_statement_in_csharp.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM