我正在制作一个计算器,该程序的一部分接受用户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.
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用数组来保存指示相应令牌优先级的值:
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]
}
Run Code Online (Sandbox Code Playgroud)
但由于这一切都假设操作符只有一个字符,这就是你可以采用这种方法.
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |