2017-04-15 111 views
-3

我必須創建這個基於控制檯的應用程序,並且我有這個問題: 我創建了一個像使用多線程的KeyListener類似的東西(不能做簡單循環,因爲有第二個線程正在運行同時)。 並且線程中的循環需要檢查按鍵是否是整數。使用多線程的控制檯應用程序中的鍵列表程序

這是什麼我不明白?

我得到這個的方式:線程內有一個無限循環,它試圖捕獲輸入,並且它在控制檯中寫入文本的input == 1。 我錯過了什麼?

static void KeyRead() 
{    
    do 
    { 
     int i = (int) Console.ReadKey().KeyChar; 
     if (i == 1) { 
      Console.Out.Write("Key 1 pressed"); 
     } 
    } while (true); 
} 

static void Main(string[] args) 
{ 
    Thread keyListner = new Thread(new ThreadStart(KeyRead)); 
    keyListner.Start();     
} 
+0

_「我不明白什麼?」_ - 你的問題是什麼?代碼的具體含義是什麼,你不希望它做什麼,你不知道如何解決? –

+0

它基本上沒有。那就是問題所在。這就像沒有「如果」的說法。 if語句之後應該如何執行代碼? 我開始申請,我按「1」,但沒有發生,雖然它應該寫「按鍵1」。 – mafiozorek

+1

即使沒有線程,您的程序也不會運行。 http://stackoverflow.com/questions/28955029/how-do-i-convert-a-console-readkey-to-an-int-c-sharp –

回答

2

KeyChar返回類型和鑄造INT,表示字符返回Unicode值的值。但性格'1'unicode value 49,而不是1所以,你必須修改條件比較是eqaual至49,而不是1

static void KeyRead() 
{ 
    do 
    { 
     int i = (int)Console.ReadKey().KeyChar; 
     if (i == 49) 
     { 
      Console.Out.Write("Key 1 pressed"); 
     } 
    } while (true); 
} 

但要完全避免這個整數轉換和比較就顯得尤爲明顯字符直接:

static void KeyRead() 
{ 
    do 
    { 
     char c = Console.ReadKey().KeyChar; 
     if (c == '1') 
     { 
      Console.Out.Write("Key 1 pressed"); 
     } 
    } while (true); 
}