2016-03-30 36 views
-1

編寫一個函數,以編譯器的代碼行的形式獲取字符串,並且每當我輸入一個以空格或分號結尾的字符串(因爲每行代碼都是用我的語言寫的),我得到在第3行以下錯誤:字符串以「;」結尾時出現子串錯誤或「」

System.ArgumentOutOfRangeException了未處理

索引和長度必須引用位置的字符串內。

我總是收到這個錯誤,如果我在最後一個「;」或「」字符串。例如,如果我輸入「a = b;」它會讀取a = b部分,並將它們放到我的符號表中並識別分隔符「=」,但一旦到達「;」就會給我一個錯誤。如果我輸入「a = b」(沒有分號),它會在第二個「」之後給出錯誤而根本不讀「b」。如果我輸入2行代碼「a = b;」和「c = 1;」它只會在第二行代碼後出現錯誤。

private static void readChar(
    ref int IX, ref string sentence, ref string testChar, ref int inputType) 
{ 
    testChar = sentence.Substring(IX, 1); 
    IX++; 
    int IX2 = 0; 
    int IX3 = 0; 

    if ("|*/[email protected]#$%^&(),`=".Contains(testChar)) 
    { 
     inputType = 5; 
    } // delimiter 

    else if (Char.IsDigit(testChar, IX2)) 
    { 
     inputType = 3; 
     IX2++; 
    } // numeric   

    else if (Char.IsWhiteSpace(testChar, IX3)) 
    { 
     inputType = 6; 
     IX3++; 
    } // space 

    else if (testChar == ";") 
    { 
     inputType = 7; 
    } // semicolon   
    else 
    { 
     inputType = 1; 
    } // end alpha 
} 

示例代碼調用readChar:

switch (inputType) 
      { 
       case 1: // alpha 
        { 
         convertCharToInt(ref inputChar, ref X); 
         wordTotal = wordTotal + X; 
         word = word + inputChar; 
         readChar(ref sentenceIX, ref sentence, ref inputChar, ref inputType); 

         while ((inputType != inputBreakChar) & (inputType != inputDelimeter) & (inputType != inputSemiColon)) //(inputType == 1) 
         { 
          convertCharToInt(ref inputChar, ref X); 
          wordTotal = wordTotal + X; 
          word = word + inputChar; 
          readChar(ref sentenceIX, ref sentence, ref inputChar, ref inputType); 
         } // end while inputType 

         calcSymbolTableIX(ref symbolTable, ref wordTotal, ref R); 
         setSymbolTableIX(ref symbolTable, ref symbolTableName, ref word, ref R); 

         word = ""; 
         break; 
        } // end case 1 
+0

如果要編寫解析器,請考慮使用解析器生成器工具包(GOLD Parser,ANTLR等)。 – Lucero

+0

你可以顯示調用readChar的代碼嗎? – sr28

+0

當然可以。從我們的講師給我們的模板中使用這段代碼,由於我在網絡領域工作,並沒有進行編程幾年,我現在正在做的課程只是把我們引向深層,並希望我們開發一個編譯器爲我們自己的編程語言。我認爲課程不允許使用解析生成器工具包。在某些調用代碼中進行編輯。 – Rokudo

回答

2

,你可以添加一個檢查,如果這是字符串由

if(IX == sentence.Length - 1) 
    testChar = sentence.Substring(IX); 
else if(IX < sentence.Length - 1) 
    testChar = sentence.Substring(IX, 1); 
+0

這不會解決問題,因爲它和以前完全一樣。只要'IX'是'> = sentence.Length',你的代碼也會拋出。 – Lucero

+0

你的編輯使它更糟糕,因爲現在當'IX> = sentence.Length'時你不會改變'testChar',所以它會保持它以前的值(它作爲'ref'傳入到方法中)。問題不在於這個電話 - 這是海報未顯示的缺失/錯誤放棄條件。 – Lucero

+0

這實際上確實解決了這個問題,謝謝。 – Rokudo

0

你需要證明你的休息狀態的終點;只要IX到達最後一個字符,那麼如果您在此時再嘗試一個字符,就會得到上述異常。由於索引是基於0的,因此您的循環(我假設您有)必須儘快停止,並且不僅在更大時纔會停止。除了這

,你要Char.IsDigitChar.IsWhitespace電話斷了,你需要通過0作爲第二個參數,而不是IX2IX3

相關問題