[英]Testing what a String token holds
我正在制作一個計算器,該程序的一部分接受用戶String
輸入並將其標記化(使用我自己的Tokenizer
類實現)。 因此,現在我有一堆Token
對象,我想測試它們中的每個對象以查看它們是否包含數字或運算符。
有沒有一種方法可以測試它們是否包含運算符(即+,-,*,/,=,(,)等)
if (token.equals("+") || token.equals("-") || ...
,依此類推,對於每個運算符,這些Token
對象都是String
類型的。
如果它們都是單字符字符串,則可以執行以下操作:
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]
}
但是,由於所有這些都假定運算符只是一個字符,因此這與您可以采用的方法差不多。
您也可以為此使用String包含。
String operators = "+-*/=()";
String token ="+";
if(operators.contains(token)){
System.out.println("here");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.