c#判断闰年月份,练习if else /switch/try catch finally语句

循环内声明的变量作用域为循环内

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入年份!");
            string year = Console.ReadLine();
            Console.WriteLine("请输入月份!");
            string month = Console.ReadLine();
            try   //try遇到异常即停止,抛出异常
            {
                int years = Convert.ToInt32(year);
                int months = Convert.ToInt32(month);
                int day = 0;
                if ((years % 400 == 0) || (years % 4 == 0 && years % 100 != 0))
                { //闰年的判断条件
                    switch (months)
                    {
                        case 2:
                            day = 29;
                            break;
                        case 4: //同样的判断条件这样用
                        case 6:
                        case 9:
                        case 11:
                            day = 30;
                            break;
                        default:
                            day = 31;
                            break;
                    }
                }
                else
                {
                    Console.WriteLine("不是闰年!");

                }
            }
            catch (Exception e)
            {

                Console.WriteLine("出现年月份异常!" + e);
            }

            Console.ReadKey();//不一闪而过


        }


    }

}

  

posted @ 2021-01-26 20:12  遥月  阅读(359)  评论(0)    收藏  举报