import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CalculatorDemo { public static void main(String args[]){ String expression = "1 + ( ( 2 + 3 ) * 4 ) - 5 "; Calculator c = new Calculator(expression); String s = c.transfertosuffix(c.expression); System.out.println(s); System.out.println("****************"); String result = c.calculateResult(s); System.out.println("result="+result); } } class Calculator{ String[] expression; public Calculator(String str){ expression = str.split(" "); } public static HashMap<String, Integer> operWithPriority = new HashMap<String, Integer>(); public static void getOper(){ operWithPriority.put("+",1); operWithPriority.put("-",1); operWithPriority.put("*",2); operWithPriority.put("/",2); operWithPriority.put("%",2); } public double calculate(String num1,String num2, String oper){ double num1double = Double.parseDouble(num2); double num2double = Double.parseDouble(num1); double result = 0; switch(oper){ case "+": result = num1double+num2double; break; case "-": result = num1double-num2double; break; case "*": result = num1double*num2double; break; case "/": result = num1double/num2double; break; case "%": result = num1double%num2double; break; } return result; } public String calculateResult(String suffixStack){ Mystack my= new Mystack(suffixStack.length()); String[] strs = suffixStack.split(" "); String patterns = "^[0-9]+.?[0-9]*$"; Pattern p = Pattern.compile(patterns); double result = 0 ; for(int i=0;i<strs.length;i++){ String temp = strs[i]; Matcher m = p.matcher(temp); if(m.matches()){ my.push(temp); }else{ String num1 = my.pop(); String num2 = my.pop(); result = calculate(num1, num2, temp); my.push(Double.toString(result)); } } return my.pop(); } public String transfertosuffix(String[] str){ getOper(); Mystack operstack= new Mystack(str.length); Mystack resultstack = new Mystack(str.length); for(int i=0;i<str.length;i++){ String tempdata = str[i]; if(operWithPriority.containsKey(tempdata)){ if(operstack.isEmpty() || "[".equals(operstack.peek())||"(".equals(operstack.peek())) { operstack.push(tempdata); }else { String strintopstack = operstack.peek(); System.out.println(strintopstack); int topstackPriority = operWithPriority.get(strintopstack); int currentPriority = operWithPriority.get(tempdata); while (currentPriority<=topstackPriority && !operstack.isEmpty() && !("[".equals(operstack.peek())||"(".equals(operstack.peek()))) { strintopstack = operstack.pop(); resultstack.push(strintopstack); if(!operstack.isEmpty() && !("[".equals(operstack.peek())||"(".equals(operstack.peek()))) { System.out.println("I am here"+operstack.peek()); topstackPriority = operWithPriority.get(operstack.peek()); } } operstack.push(tempdata); } }else if(tempdata.equals("(") || tempdata.equals("[")){ operstack.push(tempdata); } else if(tempdata.equals(")")){ String opers = operstack.pop(); while(!"(".equals(opers)){ try{ resultstack.push(opers); opers = operstack.pop(); }catch(Exception e){ System.out.println("not matched small bracket ("); return "not appropriated expression,missing small brackets"; } } } else if(tempdata.equals("]")){ String opers = operstack.pop(); while(!"[".equals(opers)){ try{ resultstack.push(opers); opers = operstack.pop(); }catch(Exception e){ System.out.println("not matched bracket ["); return "not appropriated expression,missing brackets"; } } } else{ String pattern = "^[0-9]+.?[0-9]*$"; Pattern p = Pattern.compile(pattern); Matcher matcher = p.matcher(tempdata); if(matcher.matches()){ resultstack.push(tempdata); }else{ throw new RuntimeException("not correct operator or numbers: "+tempdata); } } } while(!operstack.isEmpty()){ resultstack.push(operstack.pop()); } return resultstack.reverse(); } } class Mystack{ String[] stacks; int front; public Mystack(int len){ stacks = new String[len]; front = -1; } public boolean isFull(){ return front==stacks.length-1; } public boolean isEmpty(){ return front ==-1; } public void push(String value){ if(isFull()){ System.out.println("current stack is full"); return; } front = front +1; stacks[front] = value; } public String pop(){ if(isEmpty()){ throw new RuntimeException("current stacks is empty"); } String value = stacks[front]; front = front-1; return value; } public String reverse(){ StringBuilder str = new StringBuilder(""); if(isEmpty()){ System.out.println("curent stack is null"); return null; } for(int i=0;i<front+1; i++){ // System.out.print(stacks[i]+" "); str.append(stacks[i]+ " " ); } return str.toString(); } public String peek(){ if(isEmpty()){ throw new RuntimeException("current stacks is empty"); } String value = stacks[front]; return value; } }
带括号的中缀计算表达式转逆波兰表达式同时计算结果
最新推荐文章于 2024-07-24 21:47:59 发布