我有一個hw任務,要求將中綴表達式轉換爲後綴表達式。將字符推入堆棧是否會改變它來自的字符串?
編輯: 什麼是假設發生: 輸入:(5)輸出:5;輸入:(1 + 1)輸出:11+;輸入=((9/3)-2) 輸出= 93/2 與此代碼會發生什麼:輸入:(5)(代碼保持運行)
我已經調試它,這個問題似乎我第二次循環。它只是保持循環,我不確定爲什麼。我以爲推子到堆棧更新循環,改變從字符串(5)5)
// data fields
StackInterface<String> stack = new ArrayStack<String>();
String output = "";
int first = 0;
int second = 1;
String oneChar = infixExpression.substring(first,second);
//while
while (infixExpression.length()>0){
while(oneChar.equals("(")){
stack.push(oneChar);
first ++;
second ++;
}
//if char is), pop off stack while char is not (
//add to string operators, add to output
while(oneChar.equals(")")){
while (oneChar != "(" && stack.empty() == false){
String popOperator = stack.pop();
output = output + popOperator;
//moves to next char of String
first ++;
second ++;
}//end of while loop
}
while((oneChar == "*") || (oneChar == "/") || (oneChar == "%") || (oneChar == "+") ||(oneChar == "-")){
stack.push(oneChar);
//moves to next char of String
first ++;
second ++;
}
//error checking input is int
try{
Integer.parseInt(oneChar);
output = output + oneChar;
//moves to next char of String
first ++;
second ++;
} catch (InputMismatchException e){
System.out.print("Not a valid expression");
}
}//end of while loop
System.out.print("Postfix Expression: " + output);
}
你說你不認爲你做得對。如果您向我們提供了幾個您正在爲此代碼提供的表達式來測試它的示例,那麼您的代碼是什麼與您期望它執行的操作有什麼關係。參見[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)。 –