好吧,有問題的問題。我知道。基本的響應可能是將字符串轉換爲Ints
Convert.ToInt32(string);
但自然,C#會做每一個自然過程,以確保不會發生。
這裏是我的代碼:
while (true)
{
while (true)
{
//ask for time
Console.WriteLine("What is the hour?");
Console.WriteLine();
string s = Console.ReadLine();
//convert input to int
YourTime.nHour = Convert.ToInt32(s);
//check to see if it's legal
if ((YourTime.nHour <= 12) || (YourTime.nHour > 0))
{
break;
}
//etc etc code
}
}
我想,以確保輸入是一個實際小時。當我運行這段代碼,它總是標示出if()語句爲「真」和休息,即使我輸入類似-13或99
我敢肯定有一個簡單的替代品「Convert.ToInt32( 「),但說實話,似乎我已經嘗試了一切。我決定最好按照知道手邊代碼的人的指導進行操作。
[編輯] - 錯誤的算子,不是轉換。感謝所有幫助過的人!
請參閱[Int32.TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) – drew010 2012-01-30 02:36:47
什麼是YourTime?你創建的CLass? – Anthony 2012-01-30 02:39:33
沒關係,有人已經回答了我要回復的內容 – Anthony 2012-01-30 02:43:36