C# 練習題 (1)

C# 練習題 (1)

練習題 (1): Display series of numbers (1,2,3,4, 5....etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key).

這題目感覺應該是不難才對,就是跑一個無窮迴圈,並且印出一連串遞增的數值,直到有人按下 ESC 鍵程式就停止。

但是,第一版

程式碼變成跑一個無窮迴圈,每當使用者按下任一按鍵,數值就會地增並且列印出來。直到,使用者按下 ESC 鍵,才會停止程式。(按鍵讀取參考:ConsoleKey 列舉與 ConsoleKeyInfo 類別)

或許使用 Thread 的方法,可以一邊遞增數值,另一邊偵測使用者是否按 ESC 鍵,就可以解決這個問題吧。

第二版 程式,已經正常運作。

第一版程式碼:

   1:  using System;
   2:   
   3:  namespace InfiniteLoop
   4:  {
   5:      public class Program
   6:      {
   7:          public static void Main(string[] args)
   8:          {
   9:              int i = 1;
  10:              ConsoleKeyInfo cki = new ConsoleKeyInfo();
  11:              while (cki.Key != ConsoleKey.Escape)
  12:              {
  13:                  cki = Console.ReadKey(true);
  14:                  Console.WriteLine(i.ToString());
  15:                  i++;
  16:              }
  17:          }
  18:      }
  19:  }

第二版:

   1:  using System;
   2:  using System.Threading;
   3:   
   4:  namespace InfiniteLoop
   5:  {
   6:      public class Program
   7:      {
   8:          public static void startThread()
   9:          {
  10:              int i = 1;
  11:              while (true)
  12:              {
  13:                  Console.WriteLine(i.ToString());
  14:                  i++;
  15:              }
  16:          }
  17:   
  18:          public static void Main(string[] args)
  19:          {
  20:              Thread t = new Thread(new ThreadStart(startThread));
  21:   
  22:              t.Start();
  23:              ConsoleKeyInfo cki = new ConsoleKeyInfo();
  24:              while (cki.Key != ConsoleKey.Escape)
  25:              {
  26:                  cki = Console.ReadKey(true);
  27:              }
  28:              t.Abort();
  29:   
  30:              Console.WriteLine("Program ends");
  31:          }
  32:      }
  33:  }