值得注意的是闰年2月份有29天,平年28天,用到了上一篇怎么判断输入年份是平年还是闰年
//判断每年的每个月有多少天,初始化变量
int year
= 2016;
int month = 1;
Console.WriteLine("请输入年份:");
string strYear = Console.ReadLine();
//验证年份格式输入是不是正确
CheckYear(strYear);
year = Convert.ToInt32(strYear);
//输入月份
Console.WriteLine("请输入月份:");
string
strMonth = Console.ReadLine();
//验证输入的月份是不是正规的月份,不对,直到输入正确为止
CheckMonth(strMonth);
//根据月份不同,判断天数为多少天
month = Convert.ToInt32(strMonth);
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Console.WriteLine("31天");
break;
case 2:
//判断是不是闰年
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
{
Console.WriteLine("29天");
}
else
{
Console.WriteLine("28天");
}
break;
default:
Console.WriteLine("30天");
break;
}
Console.ReadKey();
///
/// 验证年份是不是正确格式
///
///
public static void CheckYear(string strYear)
{
try
{
int year = Convert.ToInt32(strYear);
if (year <= 0)
{
Console.WriteLine("输入年份格式不正确,请重新输入!");
strYear = Console.ReadLine();
CheckYear(strYear);
}
}
catch (Exception)
{
Console.WriteLine("输入年份格式不正确!请重新输入!");
strYear = Console.ReadLine();
CheckMonth(strYear);
}
}
///
/// 验证月份是不是正确格式
///
///
public static void CheckMonth(string strMonth)
{
try
{
int month = Convert.ToInt32(strMonth);
if (month > 12 || month <= 0)
{
Console.WriteLine("输入月份格式不正确,请重新输入!");
strMonth = Console.ReadLine();
CheckMonth(strMonth);
}
}
catch (Exception)
{
Console.WriteLine("输入月份格式不正确!请重新输入!");
strMonth = Console.ReadLine();
CheckMonth(strMonth);
}
}
Main方法中代码
两个验证格式的函数