简体   繁体   English

在C#中从控制台验证DateTime输入

[英]Validating DateTime Input from Console in C#

In a bid to learn C# in a hands-on manner, I started working through these assignments I found online... 为了动手学习C#,我开始完成在网上找到的这些作业。

http://www1.cs.columbia.edu/~lok/csharp/assignments.html http://www1.cs.columbia.edu/~lok/csharp/assignments.html

I am stuck on Exercise 1, Question 3. How can I request a date from the console and then check against given criteria? 我被限制在练习1,问题3上。如何从控制台请求日期,然后根据给定的条件进行检查? In this case, check if the date is after today and provide an 'invalid' message if true. 在这种情况下,请检查日期是否在今天之后,如果为true,则提供“无效”消息。

My code currently looks like the below. 我的代码当前如下所示。 I feel like the logic is there, but something to do with scope won't let it compile - the userBirthdate seems inaccessible outside of the loop. 我觉得逻辑已经存在,但是与范围有关的事情不会让它编译-循环外似乎无法访问userBirthdate。

I'm sure there's also a much simpler solution. 我敢肯定,还有一个更简单的解决方案。

Any help greatly appreciated - thanks guys! 任何帮助,不胜感激-谢谢大家!

        //Set today's date as a variable            
        DateTime todayDate = DateTime.Today;
        DateTime userBirthdate;

        //Ask user for birth date
        Console.Write("Please enter your date of birth (dd/mm/yy):  ");

        //Validate the input and set as a variable
        bool inputValid = false;
        while (inputValid != true)
        {
            if (DateTime.Parse(Console.ReadLine()) > todayDate)
            {
                Console.Write("Invalid Date.  Please enter your date of birth (dd/mm/yy):  ");
            }
            else
            {
                userBirthdate = DateTime.Parse(Console.ReadLine());
                Console.WriteLine(userBirthdate);
                inputValid = true;
            }
        }

        //Calculate user age
        int userAge = todayDate.Year - userBirthdate.Year;
        if (userBirthdate > todayDate.AddYears(-userAge)) userAge--;

        //Output
        Console.WriteLine("You are {0} years old!", userAge);
        Console.ReadLine();

You need to initialize userBirthdate outside of the loop: 您需要在循环外初始化userBirthdate

    DateTime userBirthdate = DateTime.MinValue;

The value doesn't matter since you're going to assign it a value within the while loop, but the compiler can't determine that without doing more static analysis than it's designed for. 该值无关紧要,因为您将在while循环内为其分配一个值,但是如果不进行比其设计目的更多的静态分析,编译器将无法确定该值。

There are several other issues, but that should solve the compilation problem. 还有其他几个问题,但这应该可以解决编译问题。

As you are not initialising the variable userBirthdate , the compiler is giving you a warning when you try to use it later. 由于您没有初始化变量userBirthdate ,因此以后您尝试使用它时,编译器会向您发出警告。 Set it to a value first or change your logic: 首先将其设置为值或更改逻辑:

DateTime userBirthdate = DateTime.Today;

Few things (also initliaze the userBirthDate as pointed out in other posts: 很少的事情(也初始化其他用户指出的userBirthDate

  1. Use DateTime.TryParse(Console.ReadLine(), out userBirthdate) to see if it's a valid DateTime. 使用DateTime.TryParse(Console.ReadLine(), out userBirthdate)来查看它是否为有效的DateTime。 If you do this right away you might not even need to initialize userBirthdate 如果立即执行此操作,则可能甚至不需要初始化userBirthdate
  2. Check if it's > DateTime.Now to make sure it's not in future. 检查它是否是> DateTime.Now ,以确保它不在将来。
  3. Do use the Subtract method to see if it's too long ago in the past. 请使用Subtract方法查看它是否在过去太久了。 It gives you a TimeSpan object which you can use to make sure it's not very old like 135 years or so. 它为您提供了一个TimeSpan对象,您可以使用该对象来确保它不是很旧,例如135年左右。

In addition to the other answers, you're calling Console.ReadLine() twice: once when you read to check and validate that the input isn't greater than today's date and again when assigning it to userBirthdate. 除了其他答案外,您还要调用Console.ReadLine()两次:一次是在阅读以检查并确认输入的数据不大于今天的日期时,一次是在将其分配给userBirthdate时。 You should assign it first and then do validation, otherwise, your program will hang because it is waiting for more input from the user. 您应该先分配它,然后再进行验证,否则,您的程序将挂起,因为它正在等待用户的更多输入。

while (inputValid != true)
{ 
    userBirthdate = DateTime.Parse(Console.ReadLine());

    if (userBirthdate > todayDate)
    {
        Console.Write("Invalid Date.  Please enter your date of birth (dd/mm/yy):  ");
    }
    else
    {
        Console.WriteLine(userBirthdate);
        inputValid = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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