我有一个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)。 –