Part B – A Simple Calculator Program

Design and implement a simple mathematical expression calculator using the Stack data structure.
The mathematical expressions used in this assignment are made up of:
the operators '+', '-', '*' and '/',
parentheses '(' and ')',
and
operands which consist of integer numbers (single or multi-digit).
The mathematical expressions are in infix format, and the operators '*', '/' have higher precedence than
the operators '+', '-'. The mathematical expressions contain no unary operators and no spaces.
For this question, you need to write a program called Calculator, which
1) checks the syntax of the expression, and converts the infix form into its equivalent postfix
form (using spaces to separate the numbers and operators);
2) calculates the value of the mathematical expression (after it has been converted into postfix
form) and prints the result. Your program must compute the value of the expression correctly.
The mathematical expression in infix form is passed to the program as a command line argument.
Your program should print the infix expression, the postfix expression and the calculated value. You
are required to use the stack data structure to solve this problem. Two example outputs using the
Calculator program are shown below:
c:\105\A2java Calculator (8+12)*3/(14-9)
A simple calculator by abdc001.
Evaluating ...
Infix Expression: (8+12)*3/(14-9)
Postfix Expression: 8 12 + 3 * 14 9 - /
Result: 12.0
Note that syntax errors in the user input expressions should be detected, e.g.,
c:\105\A2java Calculator 5+(2-4/5*6
A simple calculator by abdc001.
Evaluating ...
Infix Expression: 5+(2-4/5*6
Syntax error: brackets mismatch - too many open brackets
Hints • Use a Stack structure to convert an infix expression to its postfix form, and then use a Stack
structure to compute the value of the postfix expression (algorithms are taught in the lectures).
• In the case of checking syntax errors of an infix mathematical expression, there are five major
types of errors that you should consider:
 invalid inputs, e.g., non-digit or other characters. Note: a constant indicating the valid
characters might be useful in your program, e.g.,
final String ALL_VALID = "0123456789+-/*()";
 brackets mismatch, e.g., too many open bracket, too many closing bracket;
 missing operand, e.g., two consecutive operators, '(' followed by operator, operator
followed by ')', expression end with '(', empty bracket '( )', expression begin with ')',
expression begin with operators, expression end with operators;
 missing operator, e.g., digit followed by '(', ')' followed by digit, ')' followed by '(';
 division by zero, e.g., '/' followed by 0;
COMPSCI 105 - A2 7
Notes For Part B • Your program must use the StackReferenceBased class to solve the problem.
• For this question, you should submit the Calculator.java class.
• Your UPI must appear in the output, as shown in the example above.
FIND ATTACHED FOR SOLUTION
Powered by