java - How do I handle digits in a reverse polish notation calculator? -
import java.util.arraylist; import java.util.linkedlist; import java.util.list; import java.util.scanner; import java.util.stack; public class postfixeval { static scanner input = new scanner(system.in); static string expression; static stack<integer> calcstack = new stack<integer>(); static list<string> expressionlist = new arraylist<string>(); static boolean flag = false; public static void main(string[] args) { system.out.print("enter expression: "); while (flag == false){ expression = input.next(); system.out.println(""); expression = whitespaceremover(expression); if (expression.substring(expression.length() - 1) == ";"){ expressionlist.add(expression); } else if (expression.substring(expression.length() - 1) == "@"){ expressionlist.add(expression); flag = true; } else { system.out.println("not valid expression (must end in ; or @)"); } } calc(expressionlist); } public static void calc(list<string> list){ (int i=0;i<list.size();i++){ string currentexpression = list.get(i); (char ch : currentexpression.tochararray()){ if (ch == '+'){ calcstack.push(calcstack.pop()+calcstack.pop()); system.out.println("pop r1"); system.out.println("pop r2"); system.out.println("add r1, r2"); system.out.println("push r1"); } else if (ch == '-') { int temp = calcstack.pop(); calcstack.push(calcstack.pop() - temp); system.out.println("pop r2"); system.out.println("pop r1"); system.out.println("sub r1, r2"); system.out.println("push r1"); } else if (ch == '*') { calcstack.push(calcstack.pop() * calcstack.pop()); system.out.println("pop r1"); system.out.println("pop r2"); system.out.println("mult r1, r2"); system.out.println("push r1"); } else if (ch == '/') { int temp = calcstack.pop(); if(temp != 0){ calcstack.push(calcstack.pop() / temp); system.out.println("pop r1"); system.out.println("pop r2"); system.out.println("div r1, r2"); system.out.println("push r1"); }else{ system.out.println("cannot divide zero"); break; } } else if { int num = integer.parseint(ch); } } } } public static string whitespaceremover(string express){ return express.replaceall(" ",""); } }
i've been working on reverse polish notation calculator, i've ran problem. i've realised can't add numbers stack code goes through each character of each expression individually. i've thought adding each number array , converting int, i'm not sure how i'd go doing that. appreciated.
thanks.
Comments
Post a Comment