![](/img/trans.png)
[英]Int32.Parse(“356882”) generate exception System.FormatException: 'Input string was not in a correct format.'
[英]System.FormatException: Input string was not in a correct format from an int.Parse
try
{
for (int i = 0; i < 4; i++)
{
playerGuess[i] = int.Parse(Console.ReadLine()); //says this is the error
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught", ex);
Console.Read();
}
我運行此代碼,由於某種原因,它輸出以下錯誤:
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Convert.ToInt32(String value)
我嘗試了我在另一個這樣的線程上看到的修復,但我無法讓它們工作。 有任何想法嗎?
如果您提供的值無法轉換為 int,則int.Parse()
將失敗並出現異常到方法。
您可以使用int.TryParse()
代替,它通過返回指示成功的 boolean 使您可以更好地控制如何處理失敗。 您可能會顯示一條錯誤消息,並要求用戶重新提交。
string input = Console.ReadLine();
int result;
if(int.TryParse(input, out result)) // TryParse returns a boolean showing whether the parse worked
{
// then perform your behavior safely
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.