Question

In: Computer Science

Java Program to Fully Parenthesize an expression. Hi guys. I have a small task which I...

Java Program to Fully Parenthesize an expression.

Hi guys.

I have a small task which I cannot find the solution for. It involves expressions with Infix I'll need a Java Program to convert an expression,

eg. 3+6*(x-y)+x^2

to

((3 + (6 * (x-y))) + (x ^ 2))

Kindly assist. Thanks

Solutions

Expert Solution

Approach:

We will first convert all the expressions to postfix to normalize all the input expressions and then convert all the valid postfix expression back to full parenthesized expression.

CODE:

import java.util.Stack;

public class InfixPostfix {

   static boolean checkIfOperand(char x) {
       return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= 48 && x <= 57);
   }

   // Function to convert postfix expression into fully parenthesized infix
   // expression
   static String getInfix(String exprsn) {
       // create stack of string
       Stack<String> s = new Stack<String>();
       // iterate and add parenthesis to correct operand pair
       for (int i = 0; i < exprsn.length(); i++) {
           // check for operands and push to stack
           if (checkIfOperand(exprsn.charAt(i))) {
               s.push(exprsn.charAt(i) + "");
           } else {
               String op1 = s.peek();
               s.pop();
               String op2 = s.peek();
               s.pop();
               s.push("(" + op2 + exprsn.charAt(i) + op1 + ")");
           }
       }
       return s.peek();
   }

   // supporting function to determine the priority of operator
   static int priorityChecker(char ch) {
       switch (ch) {
       case '+':
       case '-':
           return 1;
       case '*':
       case '/':
           return 2;

       case '^':
           return 3;
       }
       return -1;
   }

   // Function that converts given infix expression
   static String infixToPostfixParser(String exprsn) {
       // initialize result string
       String result = "";
       // initialize empty stack of chars
       Stack<Character> stack = new Stack<>();

       for (int i = 0; i < exprsn.length(); ++i) {
           char c = exprsn.charAt(i);
           // If char is an operand, add it to result.
           if (Character.isLetterOrDigit(c))
               result += c;
           // If char is an '(', push it to the stack.
           else if (c == '(')
               stack.push(c);
           // If char is an ')', pop and result from the stack until an '(' is found.
           else if (c == ')') {
               while (!stack.isEmpty() && stack.peek() != '(')
                   result += stack.pop();

               if (!stack.isEmpty() && stack.peek() != '(')
                   return "Expression is Invalid";
               else
                   stack.pop();
           }
           // if operator is encountered
           else {
               // perform priority comparison of an operator
               while (!stack.isEmpty() && priorityChecker(c) <= priorityChecker(stack.peek())) {
                   if (stack.peek() == '(')
                       return "Expression is Invalid";
                   result += stack.pop();
               }
               stack.push(c);
           }

       }

       // pop all the operators from the stack
       while (!stack.isEmpty()) {
           if (stack.peek() == '(')
               return "Expression is Invalid";
           result += stack.pop();
       }
       return result;
   }

   // Driver code for calling post fix and infix conversion methods
   public static void main(String[] args) {
       // sample expression which is to be fully parenthesised
       String exprsn = "3+6*(x-y)+x^2";
       // Convert the given expression to postfix expression.
       String postFixExp = infixToPostfixParser(exprsn);

       // check if postfix expression is valid and not empty
       if (postFixExp != null && postFixExp.isEmpty() == false && postFixExp.toLowerCase()!="expression is invalid")
           System.out.println(getInfix(postFixExp));
       else
           System.out.println(
                   "Some error occurred during postfix conversion, please validate your expression and try again");

   }

}

RESULT:


Related Solutions

Hi guys, I'm working on an assignment for my Java II class and the narrative for...
Hi guys, I'm working on an assignment for my Java II class and the narrative for this week's program has me a bit lost. I've put the narrative of the assignment in the quotation marks below. " Included with this assignment is an encrypted text file. A simple Caesar cipher was used to encrypt the data. You are to create a program which will look at the frequency analysis of the letters (upper and lowercase) to help “crack” the code...
Hi guys, I need someone to look over a some codes. My xcoder telling I have...
Hi guys, I need someone to look over a some codes. My xcoder telling I have error(s), and I need someone to look what causing these errors. I'm leaving the codes that are giving me errors. I don't want to give my whole code away for privacy reasons. Language is C 1. #include #include #include #define MAXCHAR 50 /*Here are the structs for the monsters, regions, and commonality.*/ /*typedef struct was provide in instruction*/ typedef struct monster{ int id; char...
Hi, I would like to test a java program. I am learning linked list and going...
Hi, I would like to test a java program. I am learning linked list and going to make a linked lists for integer nodes. For instance, I am going to add the numbers 12, 13, and 16 to the list and then display the list contents and add 15 to the list again and display the list contents and delete 13 from the list and display the list contents and lastly delete 12 from the list and display the list...
Make a java program of Mickey I have the starter program but I need to add...
Make a java program of Mickey I have the starter program but I need to add eyes and a smile to it. import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import javax.swing.JFrame; public class Mickey extends Canvas { public static void main(String[] args) { JFrame frame = new JFrame("Mickey Mouse"); Canvas canvas = new Mickey(); canvas.setSize(400, 400); canvas.setBackground(Color.white); frame.add(canvas); frame.pack(); frame.setVisible(true); } public void paint(Graphics g) { Rectangle bb = new Rectangle(100, 100, 200, 200); mickey(g, bb); } public void...
: Create a Java program that will accept a regular expression and a filename for a...
: Create a Java program that will accept a regular expression and a filename for a text file. The program will process the file, looking at every line to find matches for the regular expression and display them. Regular Expression Format : The following operators need to be accepted: + - one or more of the following character (no groups) * - zero or more of the following character (no groups) [] – no negation, no character spans – the...
I have to use a sentinel while loop to complete the following task in a java...
I have to use a sentinel while loop to complete the following task in a java program, I want to see how this is executed so I can better understand how the sentinel while loop works. Thank you! Convert Lab 10 from a counter controlled WHILE loop to a sentinel WHILE loop. Do the following: Prompts the user to enter a grade or a -1 to quit. IF the user entered a -1 THEN Display a message that the User...
Good Evening Guys, It was given an assignment in which I have to implement iava object...
Good Evening Guys, It was given an assignment in which I have to implement iava object oriented programing. What I'm saying is that I wrote a restaurant order program in java but the whole code is located in main. Now, they want me to implement diferent classes (super), constructors, accesors, mutators, methods, objects, inheritance, polymorfism, overloading, overring, interfaces, and exceptions. I already wrote my program which works perfectly, I do not know how to implement all this object oriented features...
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)
Hi there, I am having difficulty with the attached homework question. If you guys could please...
Hi there, I am having difficulty with the attached homework question. If you guys could please help work through the steps. My balance sheet isn't balancing :/ These financial statement items for Fairview Corporation at year-end, July 31, 2017. Salaries and wages payable $2,080 Salaries and wages expense 57,500 Supplies expense 15,600 Equipment 18,500 Accounts payable 4,100 Service revenue 66,100 Rent revenue 8,500 Notes payable (due in 2020) 1,800 Common stock 16,000 Cash 29,200 Accounts receivable 9,780 Accumulated depreciation-equipment 6,000...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are from a file "in.dat". The file contains a sequence of infix form expressions, one per line. The character '$' is an end mark. For example, the following file has four infix form expressions: 1 + 2 * 3 ^ ! ( 4 == 5 ) $ 3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $ 77...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT