2015-05-30 20 views
1

代碼如下。 我正在編碼一個菜單,用戶鍵入一個數字來選擇一個菜單選項。它也被包含在一個while循環中,所以用戶可以一遍又一遍地重複菜單。 它通過第一個循環完美工作,但在第二個它給「輸入字符串不正確的格式。」在到Console.ReadLine()獲取「輸入字符串格式不正確。」在第二步到循環

​​

回答

1
int option = int.Parse(Console.ReadLine()); 

專注於編寫可調試代碼:

string input = Console.ReadLine(); 
    int option = int.Parse(input); 

現在您可以使用調試器,在Parse()語句中設置一個斷點。你會很容易看到爲什麼Parse()方法拋出異常。是的,它不喜歡空字符串。現在你可以在代碼中找到bug,Console.Read()要求你按下Enter鍵來完成,但只返回一個字符。 Enter鍵仍未處理,您將在下次閱讀電話時獲得。 KABOOM。

使用Console.ReadKey()取而代之取得領先。並使用int.TryParse(),這樣一個簡單的輸入錯誤不會導致程序崩潰。

1

int.TryParseint.Parse更好的方法,當你不知道用戶

int option; 
if(int.TryParse(Console.ReadLine(), out option)) 
{ 
    switch (option) 
    { 

    } 
} 
Console.Write("Press y to back to the main menu. Press any other key to quit: "); 
char againChoice = (char)Console.Read(); 
// also add read line to capture enter key press after press any key 
Console.ReadLine(); 

或更改後的菜單代碼

string againChoice = Console.ReadLine(); 
again =againChoice == "y"; 
輸入的輸入值
+0

你有點光彩,但真正的主要解決方案是'Console.ReadLine();'你添加。 –

+0

謝謝。這不是我正在尋找的答案,但你給了我很多想法。 –