Question: Modify Listing 20.12, EvaluateExpression.java, to add operators ^ for exponent and % for remainder. For example, 3 ^ 2 is 9 and 3 % 2

Modify Listing 20.12, EvaluateExpression.java, to add operators ^ for exponent and % for remainder. For example, 3 ^ 2 is 9 and 3 % 2 is 1. The ^ operator has the highest precedence and the % operator has the same precedence as the * and / operators. Your program should prompt the .user to enter an expression. Here is a sample run of the program:

Data from Listing 20.12,

1 1mport java.util.Stack; 3 publ1c class EvaluateExpression { publ1c stat1c void main(String[]

args) { 11 Check number of arguments passed 1f (args.length 1= 1)

1 1mport java.util.Stack; 3 publ1c class EvaluateExpression { publ1c stat1c void main(String[] args) { 11 Check number of arguments passed 1f (args.length 1= 1) { System.out.printin( "Usage: java EvaluateExpression \"expression\""): System.exit (1); 4 6 7 8 10 11 try { System.out.println(svaluateExpression (args[0]): 12 13 14 15 catch (Exception ex) { 16 System.out.printin("Wrong expression: " + args[0]): 17 18 19 1** Evaluate an expression / publ1c static 1nt evaluateExpression (String expression) { II Create operandStack to store operands Stack operandStack = new Stack (): 20 21 22 23 24 II Create operatorStack to store operators Stack operatorStack = new Stack (); 25 26 27 II Insert blanks around (.). +. -. 1. and expression = insertBlanks (expression); 28 29 30 II Extract operands and operators String[] tokens = expression.split(" "): 31 32 33 II Phase 1: Scan tokens for (String token: tokens) { 1f (token. length () == 0)II Blank space continue; // Back to the while loop to extract the next token else if (token.charAt(0) == + || token.charAt (0) == -') { II Process all +. -. *./ in the top of the operator stack wh1le (!operatorStack.isEmpty () && (operatorStack.peek () == '+' II 34 35 36 37 38 39 40 41

Step by Step Solution

3.34 Rating (160 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

import javautil public class Exercise2023 public static void mainString args Scanner input new ScannerSystemin SystemoutprintEnter an expression String exp inputnextLine try Systemoutprintlnexp evalua... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Introduction to Java Programming and Data Structure Questions!