import java.util.Stack;
public class 计算器 {
public static void main(String[] args) {
String formula="3+2*2";
System.out.println(a.getResult(formula));
}
private static boolean isRightFormat = true;
public static int getResult(String formula){
int returnValue = 0;
try{
returnValue = doAnalysis(formula);
}catch(NumberFormatException nfe){
nfe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
if(!isRightFormat){
System.out.println(("公式格式有误,请检查:" + formula));
}
return returnValue;
}
//先解决括号的问题
private static int doAnalysis(String formula){
int returnValue = 0;
LinkedList<Integer> stack = new LinkedList<Integer>();
int curPos = 0;
String beforePart = "";
String afterPart = "";
String calculator = "";
isRightFormat = true;
while(isRightFormat&&(formula.indexOf('(') >= 0||formula.indexOf(')') >= 0)){
curPos = 0;
for(char s : formula.toCharArray()){
if(s == '('){
stack.add(curPos);
}else if(s == ')'){
if(stack.size() > 0){
beforePart = formula.substring(0, stack.getLast());
afterPart = formula.substring(curPos + 1);
calculator = formula.substring(stack.getLast() + 1, curPos);
formula = beforePart + doCalculation(calculator) + afterPart;
stack.clear();
break;
}else{
System.out.println("有未关闭的右括号!");
isRightFormat = false;
}
}
curPos++;
}
if(stack.size() > 0){
System.out.println("有未关闭的左括号!");
break;
}
}
if(isRightFormat){
returnValue = doCalculation(formula);
}
if(returnValue==0){
returnValue =0;
}
return returnValue;
}
private static int doCalculation(String formula) {
Stack<Integer> stack = new Stack<Integer>();
int preVal = '+';//记录前一个运算符
int len=formula.length();
for (int i = 0; i < len; i++) {
char element = formula.charAt(i);
//过滤空格
if (element == ' ')
continue;
if (Character.isDigit(element)) { // 如果是数字就放入栈中
int num = 0;
while (Character.isDigit(element) && i<len) {
num = num * 10 + element - '0';
i++;
if (i < len)
element = formula.charAt(i);
}
i--;//这个是为了抵消上面for循环中的i++
//记录每个数字前面的符号,如果是乘号和除号就直接和前面的数字运算
if(preVal=='*')
stack.push(stack.pop() * num);
if(preVal=='/')
stack.push(stack.pop() / num);
//记录每个数字前面的符号,如果是加号或者减号就直接放入栈中
if(preVal=='+')
stack.push(num);
if(preVal=='-')
stack.push(-num);
}else {//记录当前的符号
preVal = element;
}
}
//再将栈中的所有元素进行加和
int res=0;
for (int num :stack) {
res+=num;
}
return res;
}
计算公式(java实现)
于 2021-07-29 20:29:54 首次发布