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