Question: Below is the java code to solve an equation, the only thing I want in it is to ask the user to enter input and

Below is the java code to solve an equation, the only thing I want in it is to ask the user to enter input and then the program will solve the equation. Thanks.

THE CODE IS BELOW......

import java.util.Stack;

public class Equation { public static void main(String[] args) { String expression = "(2+3)*(8-4)*(5-3)"; int output = evaluate(expression); System.out.println("Expression: "+expression); System.out.println("Output: "+output); } public static int evaluate(String expression) { char[] tempTokens = expression.toCharArray(); char[] tokens = new char[tempTokens.length*2]; int count = 0; for (int i=0;i

Stack values = new Stack();

Stack operator = new Stack(); for (int i = 0; i < tokens.length; i++) { if (tokens[i] >= '0' && tokens[i] <= '9') { StringBuffer sbuf = new StringBuffer(); while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9') sbuf.append(tokens[i++]); values.push(Integer.parseInt(sbuf.toString())); } else if (tokens[i] == '(') { operator.push(tokens[i]); } else if (tokens[i] == ')') { while (operator.peek() != '(') { values.push(applyOp(operator.pop(), values.pop(), values.pop())); } operator.pop(); } else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] == '*' || tokens[i] == '/') { while (!operator.empty() && hasPrecedence(tokens[i], operator.peek())) values.push(applyOp(operator.pop(), values.pop(), values.pop())); operator.push(tokens[i]); } } while (!operator.empty()) { values.push(applyOp(operator.pop(), values.pop(), values.pop())); } return values.pop(); } public static boolean hasPrecedence(char op1, char op2) { if (op2 == '(' || op2 == ')') return false; if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false; else return true; } public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) throw new UnsupportedOperationException("Cannot divide by zero"); return a / b; } return 0; } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock 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 Databases Questions!