I'm trying to implement a program that changes a prefix expression to a postfix one using recursion.
I've written what I thought would work but instead of the output ab/c*de+f*-
I get aa/aa/*aa/aa/*-
instead.
I think my code is getting stuck when I try to get the first character of String pre
or when I try to delete the first character of String pre
. Any suggestions/comments?
public class Prefix2Postfix {
public static final String prefixInput ="-*/abc*+def";
//desired postfix output is "ab/c*de+f*-"
public static void main (String[] args){
System.out.println(pre2Post(prefixInput));
}
public static String pre2Post(String pre){
//find length of string
int length = pre.length();
//ch = first character of pre
char ch = pre.charAt(0);
//delete first character of pre
pre = pre.substring(1,length);
if(Character.isLetter(ch)){
//base case: single identifier expression
return (new Character(ch)).toString(ch);
}else{
//ch is an operator
String postfix1 = pre2Post(pre);
String postfix2 = pre2Post(pre);
return postfix1 + postfix2 + ch;
}
}
}