import java.util.Stack;
import java.util.regex.Pattern;
public class StringToArithmetic{
private StringToArithmetic(){
}
public static double stringToArithmetic(String string){
return suffixToArithmetic(infixToSuffix(string));
}
public static String infixToSuffix(String infix){
Stack<Character> stack=new Stack<Character>();
String suffix="";
int length=infix.length();
for(int i=0;i<length;i++){
Character temp;
char c=infix.charAt(i);
switch (c){
case ' ':
break;
case '(':
stack.push(c);
break;
case '+':
case '-':
while (stack.size()!=0){
temp=stack.pop();
if(temp=='('){
stack.push('(');
break;
}
suffix+=" "+temp;
}
stack.push(c);
suffix+=" ";
break;
case '*':
case '/':
while(stack.size()!=0){
temp=stack.pop();
if(temp=='('||temp=='+'||temp=='-'){
stack.push(temp);
break;
}
else {
suffix+=" "+temp;
}
}
stack.push(c);
suffix+=" ";
break;
case ')':
while (stack.size()!=0){
temp=stack.pop();
if(temp=='(')
break;
else
suffix+=" "+temp;
}
break;
default:
suffix+=c;
}
}
while(stack.size()!=0){
suffix+=" "+stack.pop();
}
return suffix;
}
public static double suffixToArithmetic(String postfix){
Pattern pattern=Pattern.compile("\d+||(\d+\.\d+)");
String strings[]=postfix.split(" ");
for(int i=0;i<strings.length;i++)
strings[i].trim();
Stack<Double> stack=new Stack<Double>();
for(int i=0;i<strings.length;i++){
if(strings[i].equals(" "))
continue;
if((pattern.matcher(strings[i])).matches()){
stack.push(Double.parseDouble(strings[i]));
}
else{
double y=stack.pop();
double x=stack.pop();
stack.push(calculate(x,y,strings[i]));
}
}
return stack.pop();
}
private static double calculate(double x,double y,String simble){
if(simble.trim().equals("+"))
return x+y;
if(simble.trim().equals("-"))
return x-y;
if(simble.trim().equals("*"))
return x*y;
if(simble.trim().equals("/"))
return x/y;
return 0;
}
}
···
以上是这次计算器的代码。这个代码的主体基本是由朱思腾同学完成的,我稍微在思路和编写的过程当中提供了一点帮助。这个计算器的主要思路是来源于学姐的博客当中提到的中序表达式输入算术表达式再由后序表达式进行计算。相对来讲并不是一种特别简洁地办法,但是工作起来还是相当的给力的。可以很全面的完成题目当中提出的要求。
运行截图如下:
![](https://images2018.cnblogs.com/blog/1322852/201804/1322852-20180422225944502-2101401958.jpg)
![](https://images2018.cnblogs.com/blog/1322852/201804/1322852-20180422225958348-152886629.jpg)