Click here to Skip to main content
15,885,954 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
what i am doing is trying to ask the user for his/her birth year, month and date and calculate to give correct age

What I have tried:

using System;
namespace age
{
    public class Program
    {

        public static void Main()

        {

            string name;
            int age;
            int birthyear;

            Console.Write("Name: ");
            name = Console.ReadLine();
            Console.Write("Age: ");
            age = Convert.ToInt32(Console.ReadLine());
            Console.Write("Birth Year: ");
            birthyear = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine();
            Console.WriteLine("Name is {0}.", name);
            Console.WriteLine("Age is {0}.", age);
            Console.WriteLine("Birth year is {0}.", birthyear);

        }

    }

}
Posted
Updated 25-May-21 21:31pm
Comments
Mohibur Rashid 26-May-21 0:26am    
What happened?
Via Gonzales 26-May-21 0:28am    
in my current code it only ask for the simple stuff but does not calculate birthdate to age

First off, the way you are doing that is a ad idea - you have no verification at all of the user input, so if I enter "Hello" for my age your app will crash.
DOn't use Convert methods for user input - they always throw an exception if the conversion fails - use the TryParse methods instead.

Secondly, age, is a complication thing: not only does it potentially vary from day to day, but it can have legal implications - what you can't do today without being arrested you may be able to tomorrow, and vice versa. Just asking for a year is not enough!

Thirdly, just getting a year doesn't help much unless you validate it: if I enter "999" or "3" or "99" what should your app do with them?

So instead of that, read the whole birth date from the user and convert it to a DateTime value:
C#
DateTime dob;
while (true)
   {
   Console.Write("Please enter your date of birth: ");
   string inp = Console.ReadLine();
   if (DateTime.TryParse(inp, out dob)) break;
   Console,WriteLine($"\"{inp}\" is not a valid date!");
   }

Then you can use DateTime.Now to work out the Age.

This may help, but I'd suggest you try to get your version working before you go near it: Working with Age: it's not the same as a TimeSpan![^]
 
Share this answer
 
If you are just starting with C# there is an excellent free book you can download from .NET Book Zero by Charles Petzold[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900