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 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))", "{([]})", "{}())",...
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
In an application write a method filterStack that takes a stack of integers as a parameter...
In an application write a method filterStack that takes a stack of integers as a parameter and filters its elements (in a new Stack) in a way that places the even elements at the bottom and the odd ones at the top. The original stack should remain unchanged. You should use a queue (only one queue) as a temporary storage. Use stack and queue operations only to solve this problem. No need to write the main method. For example, if...
C++ Write a function called linearSearch that takes an array as a parameter and search for...
C++ Write a function called linearSearch that takes an array as a parameter and search for a specific value inside this parameter. The function returns the frequency of a specific value in the array. In the main function: 1. Define an array called salaries of length 5. 2. Initialize the array by asking the user to input the values of its elements. 3. Define a variable called key and ask the user to enter a value for this variable. 4....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT