我编写的代码不应接受不正确的日期格式。我的显示无效选择,但在文本文件中存储了不正确的日期格式。如果日期格式不正确,则不应将其存储在文本文件中。
using System;
using System.Collections;
using System.IO;
using System.Globalization;
class FunWithScheduling
{
public void AddView()
{
FileStream s = new FileStream("Scheduler.txt",FileMode.Append,FileAccess.Write);
StreamWriter w = new StreamWriter(s);
Console.WriteLine("Enter the Name of the Person To Be Met:");
string Name = Console.ReadLine();
Console.WriteLine("Enter the Date Scheduled For the Meeting:");
string Date = Console.ReadLine();
DateTime date;
if(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"),DateTimeStyles.None,out date))
{
Console.WriteLine("Invalid Choice");
}
Console.WriteLine("Enter the Time Scheduled For the Meeting:");
string Time = Console.ReadLine();
string line = Name + " "+ Date +" " + Time;
w.WriteLine(line);
w.Flush();
w.Close();
s.Close();
}
static void Main()
{
FunWithScheduling a = new FunWithScheduling();
a.AddView();
}
}
这个修改后的程序不起作用。虽然永远不会结束,并且不接受正确的日期格式,也不将其保存在文本文件中。
我不允许使用字符串生成器。
using System;
using System.Collections;
using System.IO;
using System.Globalization;
class FunWithScheduling
{
public void AddView()
{
FileStream s = new FileStream("Scheduler.txt",FileMode.Append,FileAccess.Write);
StreamWriter w = new StreamWriter(s);
Console.WriteLine("Enter the Name of the Person To Be Met:");
string Name = Console.ReadLine();
Console.WriteLine("Enter the Date Scheduled For the Meeting:");
string Date = Console.ReadLine();
DateTime date;
if(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"),DateTimeStyles.None,out date))
{
Console.WriteLine("Invalid date format!");
while(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"),DateTimeStyles.None,out date))
{
Console.WriteLine("Invalid Date Entered, please format MM-dd-yyyy");
Date = Console.ReadLine();
}
}
Console.WriteLine("Enter the Time Scheduled For the Meeting:");
string Time = Console.ReadLine();
string line = Name + " "+ Date +" " + Time;
w.WriteLine(line);
w.Flush();
w.Close();
s.Close();
}
static void Main()
{
FunWithScheduling a = new FunWithScheduling();
a.AddView();
}
}