方法的练习
判断年份是否是闰年的方法
static void Main(string[] args) { //写一个方法,判断年份是否是闰年 Console.WriteLine("请输入年份:"); int year= Convert.ToInt32(Console.ReadLine()); bool b=IsRun(year); if (b == true) { Console.WriteLine("是闰年"); } else { Console.WriteLine("不是闰年"); } } ////// 判定输入年份是否是闰年 /// /// 要判断的年份 /// 是否闰年 public static bool IsRun(int year) { bool b=(year % 400 == 0)|| (year % 4 == 0 && year % 100 != 0); return b; }
如果不是数字,提示用户重新输入
static void Main(string[] args) { //1 读取输入的整数 //多次调用(如果用户输入的是数字,则返回,否则提示用户重新输入) Console.WriteLine("请输入一个数字"); string input = Console.ReadLine(); int number = GetNumber(input); Console.WriteLine(number); Console.ReadKey(); } ////// 这个方法需要判断用户的输入是否是数字 /// 如果是数字,则返回 /// 如果不是数字,提示用户重新输入 /// public static int GetNumber(string s) { while (true) { try { int number = Convert.ToInt32(s); return number; } catch { Console.WriteLine("请重新输入"); s = Console.ReadLine(); } } }
只允许用户输入yes或者no,不是重新输入
static void Main(string[] args) { //只允许用户输入yes或者no,不是重新输入 Console.WriteLine("请用户输入:"); string b = IsYesOrNo(Console.ReadLine()); Console.WriteLine(b); } public static string IsYesOrNo(string s) { while (true) { if (s == "yes" || s == "no") { return s; } else { Console.WriteLine("你输入的不是yes或no,请重新输入"); s= Console.ReadLine(); } } }
计算输入数组的和
static void Main(string[] args) { //计算输入数组的和 int[] nums= { 1,2,3,4,5}; Console.WriteLine(GetSum(nums)); } public static int GetSum(int[] values) { int sum = 0; for (int i = 0; i < values.Length; i++) { sum += values[i]; } return sum; }