Question: please, update the code based on Question's request. So your your program could handle one of the following: Decimal numbers, OR Reminder (%), OR Parenthesis

please, update the code based on Question's request.

So your your program could handle one of the following:

Decimal numbers, OR Reminder (%), OR Parenthesis

-----------------------------------------------------------

import java.util.Scanner;

import java.util.Stack;

public class Evaluate {

public static void main(String[] args) {

Stack operandStack = new Stack();

Stack operatorStack = new Stack();

operatorStack.push('#');

Scanner io = new Scanner(System.in);

System.out.print("Enter an expression: ");

String input = io.next();

int len = input.length();

for (int i = 0; i < len; i++) {

//System.out.print(input.charAt(i));

char symbol = input.charAt(i);

if (!isOperator(symbol)) {

int n = Integer.parseInt(""+symbol);

operandStack.push(n);

} else {

char poppedOperator = operatorStack.pop();

if (prec(symbol) > prec(poppedOperator)) {

operatorStack.push(poppedOperator);

operatorStack.push(symbol);

} else {

int b = operandStack.pop();

int a = operandStack.pop();

if (poppedOperator == '*') {

operandStack.push(a * b);

} else if (poppedOperator == '/') {

operandStack.push(a / b);

} else if (poppedOperator == '+') {

operandStack.push(a + b);

} else if (poppedOperator == '-') {

operandStack.push(a - b);

} else {

//we will deal with it in future

}

operatorStack.push(symbol);

}

}

} //end of for loop

char poppedOperator = operatorStack.pop();

while (poppedOperator != '#') {

int b = operandStack.pop();

int a = operandStack.pop();

if (poppedOperator == '*') {

operandStack.push(a * b);

} else if (poppedOperator == '/') {

operandStack.push(a / b);

} else if (poppedOperator == '+') {

operandStack.push(a + b);

} else if (poppedOperator == '-') {

operandStack.push(a - b);

} else {

//we will deal with it in future

}

poppedOperator = operatorStack.pop();

}

System.out.println("Result = " + operandStack.pop());

}

private static int prec(char ch) {

if (ch == '*' || ch == '/')

return 10;

else if (ch == '+' || ch == '-')

return 5;

else if (ch == '#')

return 1;

else

return 0;

}

private static boolean isOperator(char ch) {

if (ch == '+' || ch == '-' || ch == '*' || ch == '/')

return true;

return false;

}

}

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!