JAVA中如何计算字符串表达式的结果,如:"2+8/2*6-12"。高手们过来看看。

来源:百度知道 编辑:UC知道 时间:2024/06/30 17:19:11
现有一字符串表达式:"2+8/2*6-12"。计算该表达式的结果。

在回答你的问题之前 做两个说明!
1. 你的输入要合法(不含字母,运算符后有且必须有数字,中间不能有空格)
import java.util.*;
import java.util.regex.*;
import java.lang.*;
public class CountExpression{
static String[] operater =new String[20];
static String[] number = new String[20];
public int countExpression(String str){

Stack countStack1 = new Stack();
Stack countStack2 = new Stack();
int result =0;
number = str.split("\\/|\\*|\\+|\\-");
operater= str.split("\\d+");
for(int i = 0; i<number.length;i++){
countStack1.push(number[i]);
if(i!=number.length-1){
countStack1.push(operater[i+1]);

}
}
while(!countStack1.isEmpty())
countStack2.push(countStack1.pop());
String op;
while(!countStack2.isEmpty()){
result=0;
op = countStack2.pop().toString();
if(op.equals("*")){
result=Integer.parseInt(cou