[英]Getting an System.FormatException in C#
我是新手,所以我不知道為什么會遇到這樣的異常,也不知道如何解釋,所以這里是代碼
using System;
namespace math
{
class Math
{
int add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Math math = new Math();
int result = 0;
for (int i = 0; i < args.Length; i++)
{
switch(args[i])
{
case "+":
result = math.add(int.Parse(args[i--]), int.Parse(args[i++]));
break;
default:
break;
}
}
Console.WriteLine(result);
Console.ReadLine();
}
}
}
這是 VS Code 的全部例外
Exception has occurred: CLR/System.FormatException
An unhandled exception of type 'System.FormatException' occurred in System.Private.CoreLib.dll: 'Input string was not in a correct format.'
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Int32.Parse(String s)
at math.Math.Main(String[] args) in D:\tmp\math\Program.cs:line 20
編輯:這是一個像“whoami”還是像“g++”這樣的命令行程序?
如果它是 C#,以下將是一個簡單的替代方法。
class Math
{
int add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Math math = new Math();
Console.Write("Enter Integer: ");
var val1 = Console.ReadLine();
int a = Convert.ToInt32(val1);
Console.Write("Enter Integer: ");
var val2 = Console.ReadLine();
int b = Convert.ToInt32(val2);
Console.Write("Enter Operation: ");
var operation = Console.ReadLine();
int result = 0;
switch(operation)
{
case "+":
result = math.add(a, b);
break;
default:
break;
}
Console.WriteLine(result);
Console.ReadLine();
}
}
您正在此處修改循環索引:
result = math.add(int.Parse(args[i--]), int.Parse(args[i++]));
這將導致您再次讀取“+”而不是您期望的數字,這就是您獲得FormatException
的原因。
將行更改為:
result = math.add(int.Parse(args[i - 1]), int.Parse(args[i + 1]));
這更容易理解並且不會與循環索引混淆。
如果有人輸入“a + b”(比如說),這仍然會失敗,因此您應該真正檢查這些值是否為整數:
int first;
int second;
if (int.TryParse(args[i-1], out first) &&
int.TryParse(args[i+1], out second))
{
result = first + second;
}
else
{
// Error: both values need to be numeric
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.