首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

仿 SQL 查詢分析器的 C# 計算器(八):詞法分析之數值工廠 TokenNumberFactory 實作

     編輯:關於C語言

TokenNumberFactory 數值工廠分析最簡單,主要判斷下一字元是否為數字或小數點。將分析得出的字串轉為 double 型別,賦值給建立的 TokenValue 物件。代碼如下:

/// <summary> 數值工廠 </summary>
class TokenNumberFactory : TokenFactory
{
    public new static void LexicalAnalysis(List<TokenRecord> TokenList, string Code, ref int Index)
    {
        int intIndexCurrent = Index; bool blnContinue = true; char chrTemp; string strTempWord;
        while (blnContinue && intIndexCurrent < Code.Length)
        {
            chrTemp = Code[intIndexCurrent];
            if (char.IsDigit(chrTemp) || chrTemp.Equals('.')) intIndexCurrent += 1;
            else blnContinue = false;
        }
        strTempWord = Code.Substring(Index, intIndexCurrent - Index);
        TokenRecord Token = ProduceToken(strTempWord, Index);
        TokenList.Add(Token);
        Index = intIndexCurrent - 1;
    }

    public new static TokenRecord ProduceToken(string TokenWord, int Index)
    {
        TokenRecord Token = new TokenValue(Index + 1, TokenWord.Length);
        Token.TokenValueType = typeof(double);
        double dblValue;
        if (double.TryParse(TokenWord, out dblValue)) Token.TokenValue = dblValue;
        else throw new SyntaxException(Index, TokenWord.Length, "運算式 " + TokenWord + " 無法轉換成數值。");
        return Token;
    }
}

透過這些「工廠」類別即可完成運算式轉記號物件清單,為程式理解運算式奠定基礎。下一篇將介紹如何將記號物件分析成樹狀圖,進而逐層求解。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved