Uploaded by Ritesh Samal

Bonus Quiz 2. PostfixEvaluation (12-02-2022)

advertisement
BONUS QUIZ #2
Due: 12:25 pm Sharp
3 points
Upload your sour code (.java file) and output screen capture (include part of your code)
11/02/2022
Sample Log
Mission
1.
2.
3.
4.
Ask the user for an postfix expression. Assume the expression is valid.
If the expression is empty, then stop running. otherwise
Evaluate the postfix expression.
repeat from 1
*The expression can contain numbers, +, -, /, *, and space(s)
*Assume numbers are single digit.
Enter a postfix expression
12+
postfix: 12+
result: 3
Enter a postfix expression
123*postfix: 123*result: -5
Enter a postfix expression
12*35*+
postfix: 12*35*+
result: 17
Enter a postfix expression
123*+
postfix: 123*+
result: 7
Enter a postfix expression
Algorithm and overall structure is shown in the next slide
Bye..
Evaluation of postfix expression
A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix expression
using Stack data structure we can use the following steps...
1.Read all the symbols one by one from left to right in the given Postfix Expression
2.If the reading symbol is operand, then push it on to the Stack.
3.If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and store the
two popped oparands in two different variables (operand1 and operand2). Then perform reading
symbol operation using operand1 and operand2 and push result back on to the Stack.
4.Finally! perform a pop operation and display the popped value as final result.
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println();
System.out.println("Enter a postfix expression");
String postfix = input.nextLine();
if (postfix.length()==0) {
System.out.println("Bye..");
break;
}
int result = postfixEvaluation(postfix);
System.out.println("postfix: " + postfix);
System.out.println("result: " + result);
} // end while
} // end main
public static int postfixEvaluation(String postfix) {
Stack<Integer> myStack = new Stack<>();
int result;
myStack.clear();
for (int k = 0; k < postfix.length(); k++) {
char c = postfix.charAt(k);
if (c >= '0' && c <= '9') {
int intValue = c-'0’ ;
myStack.push(intValue);
}
if (c == '+'|| c == '-' || c == '*' || c == '/') {
}
} // end for
return result;
} // end postfixEvaluation
Download