C# 发生参数超出范围异常 static void Main(字符串[]args) { 控制台。写线(“”); 字符串Calc=Console.ReadLine(); char[]操作数={'+','-','/','*'}; int index=Calc.IndexOfAny(操作数); 如果(索引!=-1) { 控制台写入线(计算子字符串(索引)); var thing=计算子字符串(索引); foreach(操作数中的变量x) { 如果(Calc.Substring(index).Contains(x))
在您完成计算并将C# 发生参数超出范围异常 static void Main(字符串[]args) { 控制台。写线(“”); 字符串Calc=Console.ReadLine(); char[]操作数={'+','-','/','*'}; int index=Calc.IndexOfAny(操作数); 如果(索引!=-1) { 控制台写入线(计算子字符串(索引)); var thing=计算子字符串(索引); foreach(操作数中的变量x) { 如果(Calc.Substring(index).Contains(x)),c#,C#,在您完成计算并将Calc减少到运算符左侧的部分后,您仍然在运算符之间循环。当您检查下一个运算符时,字符串中不再有运算符,即index指向字符串外部的位置 与其循环遍历运算符以查找作为运算符的运算符,只需从字符串中获取运算符: static void Main(string[] args) { Console.WriteLine(""); string Calc = Console.ReadLine(); char[] operands = { '+', '-', '/',
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));
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();
}
您是否尝试过使用IDE的调试工具逐行检查代码,以查看执行与您认为应该的不同之处?此外,您应该说明代码的哪一行引发了异常。在调试器中运行它-您正在覆盖
Calc
变量,但没有重新计算索引
。
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(); }