Search code examples
c#inputnumbersdigits

How to make sure that a 4 number input is 4 getting numbers?


My input is a year in 4 digits between 1900-3000. So the input has to be 4 digits 1994, 2022,2950.

However, how do I check if the input is only 3 digits or less or 5 digigts or more? I have alread made an if statement if it's over 1900 or 3000.

   if (YearNumb<1900 || YearNumb>3000)
        {
            Console.WriteLine("Du angav inte ett år mellan 1900 och 3000.");
            Console.ReadLine();
            return;

Solution

  • if (YearNumb<1900 || YearNumb>3000)
            {
                Console.WriteLine("Du angav inte ett år mellan 1900 och 3000.");
                Console.ReadLine();
                return;
            }
    else if (YearNumb.ToString().Length != 4)
               {
                Console.WriteLine("text");
                Console.ReadLine();
                return;
            } 
    

    Convert to string and check length.