C# 練習題 (3)
練習題 (3):Accepting series of numbers, strings from keyboard and sorting them ascending, descending order.
從鍵盤讀取使用者輸入的數值,並將所有輸入的數值【遞增排序】及【遞減排序】。該題運用泛型 List 類別,並使用其 sort 方法進行遞增排序,reverse 方法做遞減排序。
程式碼:
1: using System;
2: using System.Collections.Generic;
3:
4: namespace AcceptingList
5: {
6: public class Program
7: {
8: public static void printAll(List<int> l)
9: {
10: foreach (int v in l)
11: {
12: Console.Write("{0} ", v);
13: }
14: Console.WriteLine();
15: }
16:
17: public static void Main(string[] args)
18: {
19: int value;
20: string s;
21:
22: List<int> l = new List<int>();
23: Console.Write("Please input num or type \"q\" to quit: ");
24:
25: s = Console.ReadLine();
26: while (String.Compare(s, "q") != 0)
27: {
28: if (int.TryParse(s, out value) == true)
29: {
30: l.Add(value);
31: }
32: Console.Write("Please input num or type \"q\" to quit: ");
33: s = Console.ReadLine();
34: }
35: printAll(l);
36:
37: l.Sort();
38: printAll(l);
39:
40: l.Reverse();
41: printAll(l);
42: }
43: }
44: }