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...
: 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...
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)
**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...
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...
Writing a Java Code Requirements of the JAVA program: Your task is to calculate geometric area...
Writing a Java Code Requirements of the JAVA program: Your task is to calculate geometric area for 3 shapes(square, rectangle and circle). You need to build a menu that allows users to enter options. Possible options are 'S' for square, 'R' for rectangle and 'C' for circle. HINT: you can use switch statement to switch on string input Invalid input should throw a message for the user. Example: Invalid input, please try again Each options should ask users for relevant...
I am using Java and what do you mean samples? Creation of Program Application (Development Task...
I am using Java and what do you mean samples? Creation of Program Application (Development Task 2) This program should use a class file you create called: SavingsAccount. This class file should store the following information: Annual Interest Rate (this can be hardcoded) Starting Balance (use a constructor to accept this information) Create method to add all Deposits from Deposits.txt file. Create method to subtract all Withdrawals from Withdrawals.txt file. Create method to calculate the interest rate which is the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT