Question

In: Computer Science

Write a static method called "evaluate" that takes a string as a parameter

In Java language  

Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the expression evaluates to. The method MUST use a stack to perform the evaluation. Specifically, you should use the Stack class from the java.util package.

Also, in the same file, write a program that prompts the user to enter a postfix expression. Your program should evaluate the expression and output the result. Your program should call the "evaluate" method described above. Here are some examples:

     Postfix expression: 1 2 +     Result: 3     Postfix expression: 1 2 + 3 4 - *     Result: -3     Postfix expression: 3 4 5 + + 1 -     Result: 11

Solutions

Expert Solution



import java.util.Scanner;
import java.util.Stack;

public class PostfixExpressionSolver {
    // Method to evaluate value of a postfix expression 
    static int evaluatePostfix(String exp) {
        //create a stack 
        Stack stack = new Stack();
        String tokens[] = exp.split("\\s+");
        // Scan all characters one by one 
        for (int i = 0; i < tokens.length; i++) {

            if (tokens[i].trim().length() == 0) continue;

            char c = tokens[i].trim().charAt(0);

            // If the scanned character is an operand (number here), 
            // push it to the stack. 
            if (Character.isDigit(c))
                stack.push(c - '0');

                //  If the scanned character is an operator, pop two
                // elements from stack apply the operator
            else {
                int val1 = stack.pop();
                int val2 = stack.pop();

                switch (c) {
                    case '+':
                        stack.push(val2 + val1);
                        break;

                    case '-':
                        stack.push(val2 - val1);
                        break;

                    case '/':
                        stack.push(val2 / val1);
                        break;

                    case '*':
                        stack.push(val2 * val1);
                        break;
                }
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        String expression;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Postfix expression: ");
        expression = scanner.nextLine();
        System.out.println("Result: " + evaluatePostfix(expression));
    }
}

===========================================================

If you are satisfied with the solution,

please rate the answer.

Thanks : )


Related Solutions

Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { //...
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str). May an array of...
Write a function called fnReadInParameters() that takes as parameter(s): • a string indicating the name of...
Write a function called fnReadInParameters() that takes as parameter(s): • a string indicating the name of the parameter le This function should return a dictionary that stores all of the parameter le data of the SIR model in a format that we will describe further below.
.. Write a method called findNums that takes a two-dimension array of integers as a parameter...
.. Write a method called findNums that takes a two-dimension array of integers as a parameter and returns the number of times a two-digit number appears in the array. For example, if the array (as created by the program below) is 10 45 3 8 2 42 3 21 44 The value returned would be 5 (there are 5 two-digit numbers in the array) public class Question2 {    public static void main(String args[]){      int arr[][] = {{10, 45,...
Write a function that takes a C string as an input parameter and reverses the string.
in c++ Write a function that takes a C string as an input parameter and reverses the string. The function should use two pointers, front and rear. The front pointer should initially reference the first character in the string, and the rear pointer should initially reference the last character in the string. Reverse the string by swapping the characters referenced by front and rear, then increment front to point to the next character and decrement rear to point to the...
How do you write a Java method that is called : public static String[] noIdenticalCombine(String[] array1,...
How do you write a Java method that is called : public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str)....
Write a method called isMatch that takes a string of parentheses and check if all parentheses...
Write a method called isMatch that takes a string of parentheses and check if all parentheses match correctly. The parameter string might consist of other characters. Ignore other characters, just check the () {} [] public static boolean isMatch(String expressionLine); Use a JCF ArrayDeque or LinkedList as a stack to store all open or left parentheses. Use following main method to check your method. public static void main(String[] args) { String[] expression = new String[]{"{5*(x+2)+(y-1);}", "32*(20+(x[i]*3)-1", "((){([][])})", "({}((0))", "{([]})", "{}())",...
JAVA Arrays 4 Write a method called isPalindrome that takes a String as input and returns...
JAVA Arrays 4 Write a method called isPalindrome that takes a String as input and returns true if the String is a palindrome.
Write a RECURSIVE method that receives a string as a parameter. The method will return true...
Write a RECURSIVE method that receives a string as a parameter. The method will return true if the string received as a parameter is a palindrome and false if it is not. The method must not have any loops! In JAVA
in c++ Write a function that takes a C string as an input parameter and reverses...
in c++ Write a function that takes a C string as an input parameter and reverses the string. The function should use two pointers, front and rear. The front pointer should initially reference the first character in the string, and the rear pointer should initially reference the last character in the string. Reverse the string by swapping the characters referenced by front and rear, then increment front to point to the next character and decrement rear to point to the...
Write a function named "characters" that takes a string as a parameter and returns the number...
Write a function named "characters" that takes a string as a parameter and returns the number of characters in the input string
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT