这是我制作的代码:
public static boolean isOperator(char op){
if (op == '+' || op == '-'
|| op == '*' || op == '/'
|| op == '^'
|| op == '(' || op == ')'){
return true;
}
return false;
}
public static boolean isOperand(char op){
String numbers = "0123456789.";
int a = numbers.indexOf(op);
return a >= 0;
}
public static void main(String []args){
String exp= "15+20+(3.84*25)*(78/3.8)";
LinkedList a = new LinkedList();
for (int i = 0; i < exp.length(); i++){
if (isOperator(exp.charAt(i))){
a.add(exp.charAt(i));
} else if (isOperand(exp.charAt(i))){
int k = i;
while (k < exp.length()){//I see the length of the number
if (isOperand(exp.charAt(k))){
k++;
} else {
break;
}
}
if (k != exp.length()-1){//if it's not ad the end
a.add(exp.substring(i, k));
} else {//if it's at the end I take all the remaining chars of the string
a.add(exp.substring(i));
}
i = k-1;//i must go back since the subtring second parameter is exclusive
}
}
System.out.println(a);
}//main
这是输出:
[15, +, 20, +, (, 3.84, *, 25, ), *, (, 78, /, 3.8), )]
这正是我想要的。如您所见,我将操作数和运算符分别放入维护字符串顺序的列表中。有一种更简单的方法吗?