java calculator infix to postfix

43 Views Asked by At

My method works for (2+2)*(3+3) to 22+33+* but the issue is when I do 9/3*3 it goes to 933+/ but needs to be 93/3* need it to work both ways but stuck

I tired tracing output but when I try to adjust I end up ruining the original with ( ) to stop working simple functions seem to trip up the whole thing and idk if it simple and I might be overlooking it staring at it too long

 public String infixToPostfix(String textfield ) throws StackFullException, StackEmptyException{
       String result="";
       ArrayStack <String> operators = new ArrayStack<String>();
       String postFix = "3 2 * 1 5 * -";
       String expression = textfield;
       String delims = "+-*/() ";
       StringTokenizer strToken = new StringTokenizer(expression, delims, true);
      while(strToken.hasMoreTokens()){
        String token = strToken.nextToken();
        if (!delims.contains(token)) {
            System.out.println(token + "pop ");
            result = result + token+" ";
        }
        else if(token.equals("(")){
    operators.push(token);


        }
        else if(token.equals(")")) {
            while(!operators.peek().equals("(")) {
                String pop1 = operators.pop();
                System.out.println(pop1+"");
                result = result + pop1+" ";
            }
            String pop2 = operators.pop();
            System.out.println(pop2);
            
            

        }
        else if (delims.contains(token)) {
            System.out.println(token +"push");
            

            if(!operators.isEmpty()) {

                int newtoken =precedence(token);

                int peek = precedence(operators.peek());
                System.out.println(peek+ " <="+ newtoken);

            }
            operators.push(token);
        }
    }

       while(!operators.isEmpty()) {
        String popl = operators.pop();
        System.out.println(popl);

        result = result + popl;
    }




      return result;

}
     public  int precedence(String cc) {
    String base=cc;
    int num;
    if (base.equals("-")|| base.equals("+")) 
        num =1;
    else if (base.equals("*")|| base.equals("/")) 
        num=2;
    else if(base.equals("(")) 
        num =3;
    else 
        num=0;
    return num;
0

There are 0 best solutions below