2012-11-25 88 views
0

我正在製作一個計算器,並且該程序的一部分需要用戶String輸入並對其進行標記(使用我自己的Tokenizer類實現)。所以現在我有一堆Token對象,我想測試它們中的每一個,看它們是否擁有數字或操作符。測試什麼字符串令牌

有沒有一種方法來測試,看看他們是否持有運營商(即+, - ,*,/,=,(,)等),而不使用
if (token.equals("+") || token.equals("-") || ...等,每個操作員?這些Token對象都是String類型。

回答

5

如果他們所有的單字符字符串,你可以這樣做:

if ("+-*/=()".indexOf(token) > -1) { 

    // if you get into this block then token is one of the operators. 

} 

你可以使用一個數組來保存指示出相應令牌的優先級,太值:

int precedence[] = { 2, 2, 3, 3, 1, 4, 4 }; // I think this is correct 

int index = "+-*/=()".indexOf(token); 
if (index > -1) { 

    // if you get into this block then token is one of the operators. 
    // and its relative precedence is precedence[index] 

} 

但是,由於這一切都假設運營商只有一個角色,所以就這一點而言,您可以採取這種方法。

+0

對不起,經過測試,它確實能夠工作,但僅對於單個字符字符串發佈。 +1。 – Mordechai

+0

是的,如果令牌是運算符,那麼它們將是單個字符。這非常簡單。謝謝! +1 – yiwei

+0

此外,如果我重新命令if語句,然後根據返回的索引進行計算,我應該能夠(粗略地)確定運算符優先級以及...對嗎? – yiwei

1

您也可以使用String包含此。

String operators = "+-*/=()"; 
String token ="+"; 

if(operators.contains(token)){ 

    System.out.println("here"); 
}