問題如題。其中的“即時”是說程序可以檢測並判斷用戶所有的鍵盤按鍵。
在這先謝過各位的解答。
如果我的解釋不夠清晰的話,那么您可以看一下下面這個例子:
有這樣一個簡單的題目:從鍵盤輸入一串字符,編寫程序,去掉其中重復的字符(保留重復字符的第一個),然后將結果顯示在屏幕中。
這個題目的基本要求實現之后,我想讓用戶可以重復進行這一操作:輸入一個字符串,然后輸出處理后的字符串;然后繼續輸入……而不需要再次運行程序。
那么可以把用戶輸入、處理方法和輸出的代碼放到一個循環中,循環的條件是某個鍵盤按鍵……但這種解決方法的局限是,用戶決定是否繼續的決定權是受限制的,即用戶必須在輸入、處理和輸出這三個步驟結束之后才能決定是否繼續。下面給出代碼,可能會便於說明:
View Code
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 string strInput = string.Empty;
6
7 do
8 {
9 Console.WriteLine("\nPlease input a string:");
10 strInput = Console.ReadLine();
11 strInput = RemoveRepeatedLetter(strInput);
12 Console.WriteLine("result string:\n" + strInput);
13 } while (ContinueOrNot());
14 }
15 public static string RemoveRepeatedLetter(string strOriginal)
16 {
17 string strResult = string.Empty;
18
19 foreach (char c in strOriginal)
20 {
21 if (!strResult.Contains(c.ToString()))
22 {
23 strResult += c.ToString();
24 }
25 }
26
27 return strResult;
28 }
29 public static bool ContinueOrNot()
30 {
31 ConsoleKey c = ConsoleKey.Escape;
32
33 Console.Write("Continue, Y/N? ");
34 c = Console.ReadKey(false).Key;
35 if (c.CompareTo(ConsoleKey.N) == 0)
36 {
37 return false;
38 }
39 else
40 {
41 return true;
42 }
43 }
44 }
而與本文題目對應的,我真正想要實現的是用戶可以隨時結束,比如在輸入字符串的過程中——例如,上述代碼中的循環條件是“按鍵不是n/N”——當用戶按下n/N鍵之后,程序立即結束運行。
