2
我試圖實現一個程序,使用遞歸將前綴表達式更改爲後綴表達式。將前綴表達式轉換爲後綴
我寫了我認爲會工作,而不是輸出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;
}
}
}
啊,我的眼睛!你能修好縮進嗎? – 2010-11-09 00:39:42
對不起!我總是遇到麻煩,試圖使我的代碼顯示爲代碼。我總是最終不得不搞亂縮進。 – Bell 2010-11-09 01:38:28
嘗試選擇代碼行並按ctrl-k(或101按鈕)。 – 2010-11-09 01:41:43