参数超出范围异常发生
本文关键字:异常 范围 参数 | 更新日期: 2023-09-27 18:17:26
static void Main(string[] args)
{
Console.WriteLine("");
string Calc = Console.ReadLine();
char[] operands = { '+', '-', '/', '*' };
int index = Calc.IndexOfAny(operands);
if (index != -1)
{
Console.WriteLine(Calc.Substring(index));
var thing = Calc.Substring(index);
foreach (var x in operands)
{
if(Calc.Substring(index).Contains(x))<------------
{
Calc = Calc.Split(x)[0];
Console.WriteLine(Calc + "new");
Console.WriteLine("Working");
thing = thing.Replace(Convert.ToString(x), "");
Calc = Calc.Replace(" ", "");
Console.WriteLine("{0} first value",Calc);
Console.WriteLine("{0} operand value", x);
Console.WriteLine("{0} second value", thing);
index = Convert.ToInt32(index);
switch(x)
{
case '+':
Console.WriteLine(Convert.ToInt32(Calc) + Convert.ToInt32(thing));
break;
case '-':
Console.WriteLine(Convert.ToInt32(Calc) - Convert.ToInt32(thing));
break;
case '/':
Console.WriteLine(Convert.ToInt32(Calc) / Convert.ToInt32(thing));
break;
case '*':
Console.WriteLine(Convert.ToInt32(Calc) * Convert.ToInt32(thing));
break;
}
}
}
}
Console.ReadLine();
}
请原谅我草率的代码。我只是想知道为什么我得到一个参数超出范围的错误?老实说,我不知道我该怎么做。它就这样发生了。
在您完成计算并将Calc
约简为操作符左侧的部分之后,您仍然继续遍历操作符。当您检查下一个操作符时,字符串中不再有操作符,即index
指向字符串之外的位置。
不需要遍历操作符来查找作为操作符的操作符,只需从字符串中获取操作符:
static void Main(string[] args) {
Console.WriteLine("");
string Calc = Console.ReadLine();
char[] operands = { '+', '-', '/', '*' };
int index = Calc.IndexOfAny(operands);
if (index != -1)
{
Console.WriteLine(Calc.Substring(index));
string thing = Calc.Substring(index + 1);
char x = Calc[index];
Calc = Calc.Substring(0, index);
Calc = Calc.Replace(" ", "");
Console.WriteLine("{0} first value",Calc);
Console.WriteLine("{0} operand value", x);
Console.WriteLine("{0} second value", thing);
switch(x)
{
case '+':
Console.WriteLine(Convert.ToInt32(Calc) + Convert.ToInt32(thing));
break;
case '-':
Console.WriteLine(Convert.ToInt32(Calc) - Convert.ToInt32(thing));
break;
case '/':
Console.WriteLine(Convert.ToInt32(Calc) / Convert.ToInt32(thing));
break;
case '*':
Console.WriteLine(Convert.ToInt32(Calc) * Convert.ToInt32(thing));
break;
}
}
Console.ReadLine(); }