[英]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.