Question

In: Computer Science

Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a...

Write a program (preferably in Java) that, given an arithmetic expression,

  • first transforms it to a postfix form, and then computes its value (by using stack-based algorithms).

Assume that all the numbers in the arithmetic expression are one-digit numbers, i.e., each of these numbers is either 0, or 1, or 2, ..., or 9. For example, your program should correctly process expressions like 2+3*4, but there is no need to process expressions like 11+22.

Solutions

Expert Solution

Answer:

import java.util.Stack; 
  
class Main
{ 
    // A utility function to return precedence of a given operator 
    // Higher returned value means higher precedence 
    static int Prec(char ch) 
    { 
        switch (ch) 
        { 
        case '+': 
        case '-': 
            return 1; 
       
        case '*': 
        case '/': 
            return 2; 
       
        case '^': 
            return 3; 
        } 
        return -1; 
    } 
       
    // The main method that converts given infix expression 
    // to postfix expression.  
    static String infixToPostfix(String exp) 
    { 
        // initializing empty String for result 
        String result = new String(""); 
          
        // initializing empty stack 
        Stack<Character> stack = new Stack<>(); 
          
        for (int i = 0; i<exp.length(); ++i) 
        { 
            char c = exp.charAt(i); 
              
             // If the scanned character is an operand, add it to output. 
            if (Character.isLetterOrDigit(c)) 
                result += c; 
               
            // If the scanned character is an '(', push it to the stack. 
            else if (c == '(') 
                stack.push(c); 
              
            //  If the scanned character is an ')', pop and output from the stack  
            // until an '(' is encountered. 
            else if (c == ')') 
            { 
                while (!stack.isEmpty() && stack.peek() != '(') 
                    result += stack.pop(); 
                  
                if (!stack.isEmpty() && stack.peek() != '(') 
                    return "Invalid Expression"; // invalid expression                 
                else
                    stack.pop(); 
            } 
            else // an operator is encountered 
            { 
                while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){ 
                    if(stack.peek() == '(') 
                        return "Invalid Expression"; 
                    result += stack.pop(); 
             } 
                stack.push(c); 
            } 
       
        } 
       
        // pop all the operators from the stack 
        while (!stack.isEmpty()){ 
            if(stack.peek() == '(') 
                return "Invalid Expression"; 
            result += stack.pop(); 
         } 
        return result; 
    } 
     // Method to evaluate value of a postfix expression 
    static int evaluatePostfix(String exp) 
    { 
        //create a stack 
        Stack<Integer> stack=new Stack<>(); 
          
        // Scan all characters one by one 
        for(int i=0;i<exp.length();i++) 
        { 
            char c=exp.charAt(i); 
              
            // 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();     
    } 
    
    // Driver method  
    public static void main(String[] args)  
    { 
        String exp = "2+3*4"; 
        String postfix = infixToPostfix(exp);
        System.out.println("Postfix evaluation: "+evaluatePostfix(postfix)); 
    } 
} 

Output:

Please give thumbsup, or do comment in case of any query. Thanks.


Related Solutions

Write a program that performs the following two tasks in java Reads an arithmetic expression in...
Write a program that performs the following two tasks in java Reads an arithmetic expression in an infix form, stores it in a queue (infix queue) and converts it to a postfix form (saved in a postfix queue). Evaluates the postfix expression. Use linked lists to implement the Queue and Stack ADTs. DO NOT USE BUILT IN JAVA CLASSES
Please write a java program that has the following methods in it: (preferably in order)   a...
Please write a java program that has the following methods in it: (preferably in order)   a method to read in the name of a University and pass it back a method to read in the number of students enrolled and pass it back a method to calculate the tuition as 20000 times the number of students and pass it back a method print the name of the University, the number of students enrolled, and the total tuition Design Notes: The...
: In this assignment you will write a C++ program that evaluates an arithmetic expression (represented...
: In this assignment you will write a C++ program that evaluates an arithmetic expression (represented with an infix notation), then outputs this expression in prefix form and also outputs the result of the calculation. The program will first convert the input infix expression to a prefix expression (using the Stack ADT) and then calculate the result (again, using the Stack ADT). The details are provided in the following sections.
In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression...
In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers (to make things easier) such as (6 + 2) • 5 - 8 / 4 to a postfix expression. The postfix version (no parentheses are needed) of this infix expression is 6 2 + 5 * 8 4 / - The program should read the expression into StringBuilder or String infix and use the Stack and Stack Interface class...
Using Java preferably with Eclipse Task: Write a program that creates a class Apple and a...
Using Java preferably with Eclipse Task: Write a program that creates a class Apple and a tester to make sure the Apple class is crisp and delicious. Instructions: First create a class called Apple The class Apple DOES NOT HAVE a main method Some of the attributes of Apple are Type: A string that describes the apple.  It may only be of the following types:  Red Delicious  Golden Delicious  Gala  Granny Smith Weight: A decimal value representing...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
Using Java 8. Write a program that reads an expression in postfix notation, builds the expression...
Using Java 8. Write a program that reads an expression in postfix notation, builds the expression tree and prints the expression in prefix and infix notation and evaluates the expression. (Hint use a stack)
For this assignment you will write a class that transforms a Postfix expression (interpreted as a...
For this assignment you will write a class that transforms a Postfix expression (interpreted as a sequence of method calls) into an expression tree, and provides methods that process the tree in different ways. We will test this using our own program that instantiates your class and calls the expected methods. Do not use another class besides the tester and the ExpressionTree class. All work must be done in the class ExpressionTree. Your class must be called ExpressionTree and have...
Write a program to check given expression is valid or not.The expression consists of paranthsis like  [{(...
Write a program to check given expression is valid or not.The expression consists of paranthsis like  [{( if valid then convert into postfix expression and after conversion then evaluate postfix expession(using stack) and do not use build in stack. Use the c++ laguage.
write a program that evaluates the following arithmetic expression: ((A+B)/C)*((D-A)+E). Assign test values to the variables...
write a program that evaluates the following arithmetic expression: ((A+B)/C)*((D-A)+E). Assign test values to the variables and display the resulting value.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT