- 1 3 5 7 8 10 12的代码相同,只要写12月份就可以了
- 精简代码,30天的可以放在default里面写
- 可以把Console.WriteLine(“{0}年{1}月有{2}天”, year, month, day);放在Switch外面写
- 当用户输入格式不正确的时候可能会报异常,使用try catch 解决。
- if else 用来保证月份的值输入正确性
- 注意try结束的位置
using System;
namespace 判断闰年
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一个年份:");
try
{
int year= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入一个月份:");
try
{
int month = Convert.ToInt32(Console.ReadLine());
if(month>=1&&month<=12)
{
int day = 0;
//1 3 5 7 8 10 12的代码相同,只要写12月份就可以了
//精简代码,30天的可以放在default里面写
//可以把Console.WriteLine("{0}年{1}月有{2}天", year, month, day);放在Switch外面写
//当用户输入格式不正确的时候可能会报异常,使用try catch 解决。
//if else 用来保证月份的值输入正确性
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
// Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
break;
case 2:
if(year%400==0||(year%4==0&&year%100!=0))
{
day = 29;
}
else
{
day = 28;
}
// Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
break;
default:day = 30;
// Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
break;
}
Console.WriteLine("{0}年{1}月有{2}天", year, month, day);
}
else
{
Console.WriteLine("月份在1-12之间,输入有误,程序退出");
}
}//tr月份
catch
{
Console.WriteLine("月份输入有误,程序退出");
}
}//try 年份
catch//年份
{
Console.WriteLine("年份输入有误,程序退出");
}
}
}
}