1.輸入姓名直到輸入的是quit時(不區分大小寫),中止輸入而後顯示出輸入的姓名個數及姓名:ide
要求結果以下圖所示:ui
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //集合存放輸入的姓名 6 List<string> listName = new List<string>(); 7 //記錄輸入的姓名個數 8 int count = 0; 9 int wangCount = 0; 10 while (true) 11 { 12 Console.WriteLine("請輸入姓名:"); 13 string input = Console.ReadLine(); 14 if (input[0]=='王') 15 { 16 wangCount++; 17 } 18 count++; 19 listName.Add(input); 20 } 21 //這個是使用list的count屬性 22 //Console.WriteLine("你一共輸了{0}同窗的姓名,分別以下:", count); 23 Console.WriteLine("你一共輸了{0}同窗的姓名,分別以下:",count); 24 GetList(listName); 25 Console.ReadKey(); 26 } 27 /// <summary> 28 /// 遍歷姓名集合 29 /// </summary> 30 /// <param name="listName"></param> 31 private static void GetList(List<string> listName) 32 { 33 34 for (int i = 0; i < listName.Count; i++) 35 { 36 Console.WriteLine(listName[i]); 37 } 38 } 39 }
2.題目內容同上題,再增長一個顯示姓「王」的同窗的個數,此處不考慮複姓問題。結果以下圖:spa
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //集合存放輸入的姓名 6 List<string> listName = new List<string>(); 7 //記錄輸入的姓名個數 8 int count = 0; 9 int wangCount = 0; 10 while (true) 11 { 12 Console.WriteLine("請輸入姓名:"); 13 string input = Console.ReadLine(); 14 if (input[0]=='王') 15 { 16 wangCount++; 17 } 18 if (input.ToLower() == "quit") 19 { 20 break; 21 } 22 count++; 23 listName.Add(input); 24 } 25 //這個是使用list的count屬性 26 //Console.WriteLine("你一共輸了{0}同窗的姓名,分別以下:", count); 27 Console.WriteLine("你一共輸了{0}同窗的姓名,分別以下:",count); 28 GetList(listName); 29 //使用拉姆達表達式,能看懂就行 30 //Console.WriteLine("你輸入的姓名中姓王的有{0}個同窗", listName.Find(x => x[0] == '王').Count()); 31 Console.WriteLine("你輸入的姓名中姓王的有{0}個同窗",wangCount); 32 Console.ReadKey(); 33 } 34 /// <summary> 35 /// 遍歷姓名集合 36 /// </summary> 37 /// <param name="listName"></param> 38 private static void GetList(List<string> listName) 39 { 40 41 for (int i = 0; i < listName.Count; i++) 42 { 43 Console.WriteLine(listName[i]); 44 } 45 } 46 }
若有更好的方案,請評論,謝謝!code