Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

1. Describe the power of nonverbal communication

Answered: 1 week ago