Linked Questions

Popular Questions

I need to write a Java program that takes from the standard input a valid Right Parenthesized Infix Expression (RPIE) and outputs the equivalent Full Parenthesized Infix Expression (FPIE). For example, if the input is: a+20)/b-c)53.4-d))) , the output should be ((a+20)/((b-c)(53.4-d))).

I have tried to implement as follows but did not reach the solution. Could anyone help me?

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

public class ParenthesisCreator {

    static private String expression;
    private Stack<Character> stack = new Stack<Character>();

    public ParenthesisCreator(String input) {
        expression = input;
    }

    public String rtParenthesisInfixToFullParenthesis() {
        String postfixString = "";

        for (int index = 0; index < expression.length(); ++index) {
            char value = expression.charAt(index);
            if (value == ')') {
                stack.push(')'); 
                stack.push('(');
                Character oper = stack.peek();
                while (!stack.isEmpty()) {
                    stack.pop();
                    postfixString += oper.charValue();
                    if (!stack.isEmpty())                 
                        oper = stack.peek(); 
                }
            } else {
                postfixString += value;
            }
        }

        return postfixString;
    }


    public static void main(String[] args) {
        System.out.println("Type an expression written in right parenthesized infix: ");
        Scanner input = new Scanner(System.in);
        String expression = input.next();
        // Input: a+20)/b-c)*53.4-d)))
        // Desired output is: ((a+20)/((b-c)*(53.4-d)))
        ParenthesisCreator convert = new ParenthesisCreator(expression);
        System.out.println("This expression writtien in full parenthesized is: \n" + convert.rtParenthesisInfixToFullParenthesis());
    }

}

Related Questions