Answered! Write a java program that takes a prefix form of an expression (as a strings) as an input and output the infix form of…

Write a java program that takes a prefix form of an expression (as a strings) as an input and output the infix form of the expression

Expert Answer

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package chegg.june;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import sun.java2d.pipe.BufferedBufImgOps;

/**
*
* @author Sam
*/
public class prefix2infix {
String[] stack;
int top;

public prefix2infix() {
stack = new String[50];
top = -1;
}

private void push (String s) {
stack[++top] = s;
}

private String pop() {
return stack[top–];
}

private int size() {
return top + 1;
}

public String toInfix(String prefix) {
char lastOp = ‘ ‘;
for(int i = prefix.length()-1; i >= 0; i–) {
if (prefix.charAt(i)== ‘ ‘ )
continue;
if (prefix.charAt(i)== ‘+’ || prefix.charAt(i)== ‘-‘ || prefix.charAt(i)== ‘*’ || prefix.charAt(i)== ‘/’ ) {
String a = pop();
String b = pop();
if((lastOp == ‘+’ || lastOp == ‘-‘) && (prefix.charAt(i)== ‘*’ || prefix.charAt(i)== ‘/’))
a = “(“+a+”)” + (char)prefix.charAt(i) + “(“+b+”)”;
else
a += (char)prefix.charAt(i) +b;
lastOp = prefix.charAt(i);
push(a);
}
else
push(“”+prefix.charAt(i));
}
return pop();
}

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String prefix = br.readLine();
prefix2infix p2i = new prefix2infix();
String infix = p2i.toInfix(prefix);
System.out.println(“Infix: ” + infix);
}
}

Here you go champ. The code is handcrafted just for you. Let me knowif you are having any trouble.

Still stressed from student homework?
Get quality assistance from academic writers!