The goal of this assignment is build a stack from scratch and to use that stack to build a simple stack-based calculator.
A simple stack-based calculator works as follows:
Because the operator is entered after the operands, this kind of calculator is called a postfix calculator.
Pay attention to the order of the operands. If 5 and 3 are pushed onto the stack, 3 is at the top of the stack and is popped first when an operator is entered. If the operator is -, make sure your code computes 5 - 3 = 2, rather than 3 - 5.
Your calculator should accept the calculation to be made as command line values, that is, in the argument to main. So the above example would be expressed as the command-line arguments 5 3 - .
If an operator is found when there are 0 or 1 values on the stack (instead of 2 or more), the calculator should print "syntax error" and continue, without changing the stack. The same if the operand is not a long value and not one of the recognized operators, e.g. if the calculator is called with the command-line hello world, it will print "syntax error" twice, and exit.
Your code must use the Java Standard Library's Stack class for your stocks. Your stack stores value of type Long.
If the command-line arguments are 2 2 + , your calculator should print 4.
If the command-line arguments are 2 2 + 3 * 22 20 - / 4 % 8 ^ your calculator should print:
4 12 2 6 2 256
The initial result, 4, is the only element left on the stack after the +. Then we multiply 3 by 4 to give 12, which again is the only element left on the stack. After pushing 22 and 20, 20 is at the top of the stack, with 22 below it and 12 at the bottom of the stack. The - operator computes 22 - 20 to give 2, leaving 2 at the top of the stack and 12 below it. The next operator, /, computes 12 / 2 giving 6 as the only value on the stack. The next two arguments are 4 and modulo, so your calculator pops 4 and 6, computes 6 % 4 = 2, and pushes 2 onto the stack. The final operation computes 2^8 = 256.
Your class must be called StackCalculator.
Your code must include a public method String calculate(String[] args) which does the bulk of the work, specifically doing the calculations and returning the results. calculate() should use a StringBuilder() to create the result string incrementally as each calculation is done. To create a multi-line string, append "\n" after each result.
Your main method then simply calls calculate() giving it its own argument, and prints the result string.
Once you are done, find your src directory and navigate to edu.ics211.h10, then turn in the .java files to Laulima directly, without zipping or archiving.