再帰を使用して前置式を後置式に変更するプログラムを実装しようとしています。
私はうまくいくと思ったものを書きましたが、代わりab/c*de+f*-
に得られる出力のaa/aa/*aa/aa/*-
代わりに。
String pre
の最初の文字を取得しようとしたとき、または の最初の文字を削除しようとしたときに、コードが動かなくなったと思いますString pre
。提案/コメントはありますか?
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;
}
}
}