前言
不断的刻意练习,终究会有所得。正所谓 “ 温故而知新 ” 。
这种基础的新手教程题目,不论什么编程都有涉及。但是面对学习,应怀有一颗空杯的心去学习,方能有所得。
语法分析
本案例混用了以下三种语句。
try-catch —— 防止不正确的输入
switch-case ——确定月份的天数
if-else ——限制月份输入的区间
编程思路
1、 程序主体
先完成正常输入时的函数,其主体如下:
static void Main(string[] args)
{
Console.Write("请输入年份:");
int year = Convert.ToInt32(Console.ReadLine()); //获取 year
Console.Write("请输入月份:");
int month = Convert.ToInt32(Console.ReadLine()); //获取 month
int day = 0; //初始化天数
#region 天数判断
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{ day = 29; }
else
{ day = 28; }
break;
default:
day = 30;
break;
}//switch-case of month
Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
#endregion
}// main
2、限定输入的月份范围
使用 if-else 限定月份输入的范围,即只能为1~12。
if (month >= 1 && month <= 12)
{
switch (month)
{
...
}
}//if month
else
{ Console.WriteLine("month不在正常范围!"); }
3、加入 try-catch
为防止年份与月份输入有误,使用 try-catch 防止程序异常。最终的程序如下。
internal class day
{
static void Main(string[] args)
{
Console.Write("请输入年份:");
try
{
int year = Convert.ToInt32(Console.ReadLine()); //获取 year
Console.Write("请输入月份:");
try
{
int month = Convert.ToInt32(Console.ReadLine()); //获取 month
int day = 0; //初始化天数
if (month >= 1 && month <= 12)
{
#region 天数判断
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{ day = 29; }
else
{ day = 28; }
break;
default:
day = 30;
break;
}//switch-case of month
Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
#endregion
}//if month
else
{ Console.WriteLine("month不在正常范围!"); }
}//try month
catch
{ Console.WriteLine("Input_month Error !!"); }
}//try year
catch
{ Console.WriteLine("Input_year Error !!"); }
}// main
}
总结
上述案例是一个简单的事,虽然被复杂化,但是一件简单的事包含更多的知识才是学习的目标。
此案例应该可以运用 方法 封装代码实现程序模块化,可以试试哦!
还有一个点可以加入代码,使得程序更加严谨。
小知识
程序中花括号使用( } )了少量备注,此技巧对于大型程序特别有用,方便了解程序作用,还能防止花括号的丢失。
这也是我以"空杯心态"所学到得到一点知识,在此分享给各位。