所以我正在制作一個“機器人”程式,當機器人問你問題并且你輸入答案時。當機器人詢問您的年齡時,顯然您只能回答數字。如果您嘗試插入非數字(例如:daskjldsjal),它將產生未處理的例外。我嘗試使用TryParse,但它仍然無法正常作業。這是代碼
` //ask age
Thread.Sleep(2000);
Console.WriteLine("(OwO) How old are you? (answer only in number pleaseee)");
int age = Convert.ToInt32(Console.ReadLine());
if (!int.TryParse(Console.ReadLine(), out age))
{
Thread.Sleep(2000);
Console.WriteLine("(-w-)");
Thread.Sleep(2000);
Console.WriteLine("(-w-) I've told you to only answer in number");
Thread.Sleep(2000);
Console.WriteLine("(-w-) You are lucky my developer knows how to include a code to prevent unhandled exception.");
Thread.Sleep(2000);
Console.WriteLine("(???) Otherwise that would have crashed me!!!!");
Thread.Sleep(2000);
Console.WriteLine("(-w-) Again, how old are you? (don't forget to answer in number)");
}`
我是任何編程的新手,如果這看起來如此平凡/微不足道,我深表歉意。謝謝你。
我希望它顯示錯誤訊息(我已經告訴過你等等),而且我認為 try 和 catch 不會起作用,因為它具有稍后將被詢問的值。
uj5u.com熱心網友回復:
int age = Convert.ToInt32(Console.ReadLine());
沒用并導致錯誤
在您的嘗試決議中添加一個“int”以使其像這樣
Thread.Sleep(2000);
Console.WriteLine("(OwO) How old are you? (answer only in number pleaseee)");
if (!int.TryParse(Console.ReadLine(), out int age))
{
Thread.Sleep(2000);
Console.WriteLine("(-w-)");
Thread.Sleep(2000);
Console.WriteLine("(-w-) I've told you to only answer in number");
Thread.Sleep(2000);
Console.WriteLine("(-w-) You are lucky my developer knows how to include a code to prevent unhandled exception.");
Thread.Sleep(2000);
Console.WriteLine("(???) Otherwise that would have crashed me!!!!");
Thread.Sleep(2000);
Console.WriteLine("(-w-) Again, how old are you? (don't forget to answer in number)");
}
'Out' 關鍵字不需要初始化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/536691.html
標籤:C#细绳解析整数
上一篇:正則運算式決議自定義Apache日志,在“大小”欄位后添加欄位
下一篇:從字串中決議長格式日期
