data structure and algorithms

profileSiper
Calculator.java

package array; import java.util.Stack; public class Calculator { public static String infix2postfix(String exp) { Tokenizer tokens = new Tokenizer(exp); Stack<String> stack = new Stack<String>(); StringBuffer buffer = new StringBuffer(); while (tokens.hasNext()) { String t = tokens.next(); switch (t) { case "(": stack.push("("); break; case ")": while( !stack.peek().equals("(")) { buffer.append(" " + stack.pop()); } stack.pop(); break; case "*": case "/": if(stack.isEmpty()) { stack.push(t); } else { while(!stack.isEmpty() && !stack.peek().equals("(") && ( stack.peek().equals("*") || stack.peek().equals("/")) ){ buffer.append(" " + stack.pop()); } stack.push(t); } break; case "+": case "-": if(stack.isEmpty()) { stack.push(t); } else { while(!stack.isEmpty() && !stack.peek().equals("(") ){ buffer.append(" " + stack.pop()); } stack.push(t); } break; default: buffer.append(" " + t); } } while(!stack.isEmpty()) { buffer.append(" " + stack.pop()); } return buffer.toString(); } //The argument is an expression that is in the usual form //as that you type in a calculator //For example: 2+(3*(5-2)-4)*6 ------ infix notation //The output is the result as a double public static double eval(String exp) { //Implement this function } public static void main(String[] arg) { System.out.println(eval("1.2+3.1+(3.3-3*0.5)")); System.out.println(eval("2+(3*(5-2)-4)*6")); } }