2015-02-05 326 views
0

創建一個C#程序來提示用戶從問題的答案選項列表中選擇正確的答案,如果答案錯誤,則嘗試再次提示相同的問題循環,但它不工作,因爲它假設是。C#中char和int之間的區別#

class Program 
{ 
    static void Main(string[] args) 
    { 
     char UserChoice = ' '; 
     do 
     { 
       Console.WriteLine("What is the command keyword to exit a loop in C#?"); 
       Console.WriteLine("a.quit"); 
       Console.WriteLine("b.continue"); 
       Console.WriteLine("c.break"); 
       Console.WriteLine("d.exit"); 
       UserChoice = ' '; 
       Console.WriteLine("Please enter a b c or d"); 
       UserChoice = (char)Console.Read(); 
       switch (UserChoice) 
       { 
        case 'a': Console.WriteLine("wrong ans"); break; 
        case 'b': Console.WriteLine("wrong ans"); break; 
        case 'd': Console.WriteLine("wrong ans"); break; 
        case 'c': Console.WriteLine("right"); break; 
        default: Console.WriteLine("Bad choice {0}", UserChoice); break; 
       } 
     } while (UserChoice == 'a' || UserChoice == 'b' || UserChoice == 'd'); 
    } 
} 

但如果我使用int代替炭在該方案,並用1,2,3和4,然後該工作方案細取代的a,b,c和d。請有人可以解釋這個代碼在使用char時出了什麼問題。

+4

當你使用char時會發生什麼?你會得到錯誤?如果是這樣,錯誤是什麼? – Sefa 2015-02-05 20:54:46

+0

@ adv12他的代碼似乎是正確的。 a,b,c和d不是命令,它們是對命令含義的猜測。閱讀被問到的問題的文本。 – Servy 2015-02-05 20:58:55

+0

@Servy,是我掠過。謝謝。 – adv12 2015-02-05 20:59:36

回答

0

如果你想閱讀單個字符,你應該使用Console.ReadKey

Console.Read等待來自控制檯的輸入,這意味着讀取大多數shell中的整行內容,然後將該輸入的第一個字符的ASCII值作爲int給出。

如果只是用ReadKey你可以得到一個實際char代表按下的下一個字符,而不必擔心如何你進入一個char轉換。

+0

它不讓我使用char UserChoice = Console.Readkey();如錯誤所述 - >不能將類型System.Consolekeyinfo隱式轉換爲char。 – jay 2015-02-05 21:24:22

+0

我已經使用了ConsolekeyInfo UserChoice = Console.ReadKey();然後使用UserChoice.keyChar來使用代碼中的任何地方。 – jay 2015-02-05 21:26:02

+0

@jay是的,這是正確的。 – Servy 2015-02-05 21:26:58

相關問題