Update the following calculator program so that it can handle the power operator as well. That means, it prints 34 when

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Update the following calculator program so that it can handle the power operator as well. That means, it prints 34 when

Post by answerhappygod »

Update the following calculator program so that it can handlethe power operator as well. That means, it prints 34 when the inputstring is "3^(4-1)+7"
import java.util.*;public class Calculator { private static Scanner s = newScanner(System.in); private static int getOp(String exp, int cur){ Scanner s = newScanner(exp.substring(cur)); s.useDelimiter("[^0-9]"); return s.nextInt(); } public static int doOp(int op1, int op2, charoperator) { switch(operator) { case '+': return op1+op2; case '-': return op1-op2; case '*': return op1*op2; case '/': return op1/op2; default: return 0; } } public static int comparePrecedence(char op1, charop2) { if(op1 == '+' || op1 == '-') if(op2 == '+' || op2 =='-') return0; else return-1; else if(op2 == '+' || op2 == '-') return 1; else return 0; } public static void main(String args[]) throwsException{ Stack<Character> operators = newStack<Character>(); Stack<Integer> operands = newStack<Integer>(); while(true){ System.out.println("Please entera new expression: "); String exp = s.nextLine(); if(exp.equals("DONE")) break; for(int cur = 0; cur <exp.length();cur++){ switch(exp.charAt(cur)) { case '+':case'-':case'*':case'/': while(!operators.isEmpty() && operators.peek() !='(') if(comparePrecedence(operators.peek(),exp.charAt(cur)) >= 0) { int temp = operands.pop(); operands.push(doOp(operands.pop(),temp, operators.pop())); }else break; operators.push(exp.charAt(cur)); break; case '(': operators.push(exp.charAt(cur)); break; case ')': if(operators.peek()!= '('){ int temp = operands.pop(); operands.push(doOp(operands.pop(), temp,operators.pop())); } operators.pop();//pop the matching open parenthesis break; case ' ': case'\t': break; default://ifnumber if(Character.isDigit(exp.charAt(cur))){ int temp = getOp(exp, cur); while(cur < exp.length() &&Character.isDigit(exp.charAt(cur))) cur++; cur--; operands.push(temp); }else throw new Exception("Error: bad input"); } } int result; while(!operators.isEmpty()){ int temp =operands.pop(); operands.push(doOp(operands.pop(), temp, operators.pop())); } System.out.println("The resultis " + operands.pop()); } }}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply