Answered step by step
Verified Expert Solution
Question
1 Approved Answer
leverage ANTLR to implement a reverse polish calculator. Write code in Java ADD MORE FUNC TO THE CODE BELOW TO HANDLE: * * ( power
leverage ANTLR to implement a reverse polish calculator. Write code in Java
ADD MORE FUNC TO THE CODE BELOW TO HANDLE:
power instead of log lnsin cos tan asin, acos, and atan, sinh cosh tanh e pi
CODE
import java.util.Scanner;
import java.util.Stack;
public class Main
public static void mainString args
Scanner scanner new ScannerSystemin;
while scannerhasNextLine
String infix scanner.nextLine;
String rpn infixToRPNinfix;
double result evaluateRPNrpn;
System.out.printlninfix;
System.out.printlnrpn;
System.out.printffn result;
scanner.close; Closing the scanner to avoid resource leak
Method to convert infix expression to Reverse Polish Notation RPN
private static String infixToRPNString infix
StringBuilder result new StringBuilder;
Stack stack new Stack;
for char c : infix.toCharArray
if CharacterisDigitc c
result.appendc; Append operand directly to result
else if c
stack.pushc; Push onto the stack
else if c
while stack.isEmpty && stack.peek
result.appendappendstackpop; Append operators to result until is encountered
stack.pop; Discard
else
while stack.isEmpty && precedencec precedencestackpeek
result.appendappendstackpop; Append operators with higher or equal precedence to result
stack.pushc; Push current operator onto the stack
result.append; Append space after operator
while stack.isEmpty
result.appendappendstackpop; Append remaining operators to result
return result.toStringtrim; Return trimmed RPN expression
Method to determine precedence of operators
private static int precedencechar operator
switch operator
case :
case :
return ;
case :
case :
return ;
default:
return ;
Method to evaluate RPN expression
private static double evaluateRPNString rpn
Stack stack new Stack;
for String token : rpnsplits
if tokenmatchesdd
stack.pushDoubleparseDoubletoken; Push operands onto stack
else
double b stack.pop; Pop top two operands from stack
double a stack.pop;
switch token
case :
stack.pusha b; Perform addition
break;
case :
stack.pusha b; Perform subtraction
break;
case :
stack.pusha b; Perform multiplication
break;
case :
if b
throw new ArithmeticExceptionDivision by zero"; Handle division by zero
stack.pusha b; Perform division
break;
default:
throw new IllegalArgumentExceptionInvalid operator: token; Handle invalid operator
return stack.pop; Return final result
OUTPUInput expression Reverse Polish expression Computation result
::
sin pi :pi :sin
lne e ln
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started