5. Implement the following method. You may use the LinkedStack class and the Sta
ID: 3816750 • Letter: 5
Question
5. Implement the following method. You may use the LinkedStack class and the Stack operations of push, pop, peek, isEmpty, and size. The parameter, exp, is a String that contains a postfix expression. For simplicity, the expression contains only one-digit numbers, the binary operations + and -, and spaces. For instance, You may use the following methods of the String class: o charAt(int index)- Returns the char value at the specified index.
o length() – Returns the length of this string.
To convert characters into digits you my use getNumericValue method of Character class. E.g., Character.getNumericValue(‘5’) returns 5. T
The method specification is the following:
public static int evaluatePostfix(String exp)
// Precondition (Which is not checked): The parameter string (exp) is a
// properly formed postfix expression consisting of one-digit integers,
// the binary operations + and -, and spaces.
// Postcondition: The method has returned the value of the postfix expression.
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
Please rate my answer.
import java.util.Scanner;
import java.util.Stack;
public class PostfixEvaluation{
public static int evalPostfix(String str){
Stack<Integer> stack = new Stack<Integer>();
int i=0;
while (i < str.length()) { // iterating over all characters of postfix expression
char c = str.charAt(i);
if (Character.isDigit(c)) { // if current character is digit then push in stack
stack.push(c - '0');
i++;
continue;
}
// if current character is operator, then pop two elements from stack
int b = stack.pop();
int a = stack.pop();
if (c == '+') stack.push(a + b);
else if (c == '-') stack.push(a - b);
else if (c == '*') stack.push(a * b);
else if (c == '/') stack.push(a / b);
else if (c == '%') stack.push(a % b);
i++;
}
return stack.pop();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a valid postfix expression: ");
String postfix = sc.next();
System.out.println(evalPostfix(postfix));
}
}
/*
SAmple Output:
Enter a valid postfix expression:
12+3*
9
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.