越界异常
public override Models.CalculationNode Parse(string expression)
{
var calNode = new Models.CalculationNode();
int i = expression.Length;
char[] x = expression.ToCharArray();
string temp = "";
//Backwards assembly of the tree
//Right Node
while (!IsOperator(x[i]) && i > 0)
{
if (!x[i].Equals(' ')) temp = x[i] + temp;
i--;
}
}
我已经有一段时间没有使用树了,并且在 while 循环中遇到了越界异常。
public override Models.CalculationNode Parse(string expression)
{
var calNode = new Models.CalculationNode();
int i = expression.Length;
char[] x = expression.ToCharArray();
string temp = "";
//Backwards assembly of the tree
//Right Node
while (!IsOperator(x[i]) && i > 0)
{
if (!x[i].Equals(' ')) temp = x[i] + temp;
i--;
}
}
It has been a while since I've used trees and I'm getting an out of bounds exception in the while loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当您从
i = expression.Length
开始时,会出现 off-by-1 错误。第一个索引将立即出界。您可以将循环重写为 for 循环,如下所示:You've got an off-by-1 error when you start at
i = expression.Length
. That first index will be out of bounds right off the bat. You could rewrite the loop as a for loop like so:字符数组从 0 到 length-1
character array is from zero to length-1
您应该尝试编写
int i = x.Length - 1;
。一旦
x
包含索引从0
到x.Length - 1
的项目,x[expression.Length]
似乎只有一项超出范围。You should try writing
int i = x.Length - 1;
.As soon as
x
contains items indexed from0
tox.Length - 1
,x[expression.Length]
seems to be just one item out of bounds.我会反转测试:
因为
IsOperator
将首先被评估,并且 i 在循环结束时将为 -1 (尽管循环开始时可能遇到任何问题)。I'd reverse the test:
because the
IsOperator
will be evaluated first and i will be -1 at the end of the loop (not withstanding any problems you might have with the start of the loop).您需要:
然后在 while 循环中您将需要:
数组是基于 0 的,因此 0 是第一个位置,最后一个位置是长度减 1。
You need:
and then in the while loop you will need:
Arrays are 0 based, so 0 is the first position and the final position is the length minus 1.
您将 i 设置为从 1 开始的字符串长度。
不过,您的数组索引从 0 开始,因此当您访问末尾的元素时,您实际上是在尝试超出范围 1。这是抛出错误的循环的第一次运行。
您需要在 i 的初始化中添加 -1。
You're setting i to be the length of the string, which starts at 1.
Your array indexing starts at 0 though, so when you're accessing the element at the end, you're actually trying to go 1 beyond your bounds. It's the first run of the loop that's throwing the error.
You need to add -1 to your initialisation of i.