2010-05-04 44 views
0
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循環中出現越界異常之後,我已經有一段時間了。出境異常

回答

1

當你從i = expression.Length開始時,你已經有了1錯誤。那第一個指數將立即跳出界限。你可以重寫循環作爲一個循環,像這樣:

char[] x = expression.ToCharArray(); 
string temp = ""; 

//Backwards assembly of the tree 

//Right Node 
for (int i = x.Length - 1; i >= 0 && !IsOperator(x[i]); --i) 
{ 
    if (!x[i].Equals(' ')) temp = x[i] + temp; 
} 
+0

感謝這是更清潔 – Matt 2010-05-04 20:29:57

1

字符數組是從零到length-1的

1

你應該試着寫int i = x.Length - 1;

只要x包含索引從0x.Length - 1項目,x[expression.Length]似乎是出界,只是一個項目。

1

我會扭轉測試:

while (i >= 0 && !IsOperator(x[i])) 

因爲IsOperator將首先評估,我將是-1在循環結束(不承受任何問題,你可能有一個的開始循環)。

0

您需要:

int i = expression.Length; 

,然後在while循環,你將需要:

while (!IsOperator(x[i]) && i >= 0) 

陣列基於0 ,所以0是所述第一位置和最終位置是您正在設定我爲t的長度的長度減1

0

他字符串,它開始於1 你的數組索引從0開始的,所以當你在結束訪問元素,你實際上是試圖去超越1的邊界。這是引發錯誤的循環的第一次運行。

您需要添加-1到你我的初始化。