爲了簡單地讓你的程序做更多的事情,你可以使用一個循環來繼續操作operandStack
並將前一結果的結果推送到堆棧。我留下了我的println
聲明,以便您可以看到它的功能。此外,我修改了您的方法,以便它可以坐在獨立的main
方法中。
你應該看看Shunting-yard算法,它的實現非常有趣,它有點像你在這裏做的事情。 http://en.wikipedia.org/wiki/Shunting-yard_algorithm
public static void main(String[] args) {
Stack<Integer> operandStack = new Stack<Integer>();
Stack<Character> operatorStack = new Stack<Character>();
String input = "12 + 13 - 4";
StringTokenizer strToken = new StringTokenizer(input, " ", false);
while (strToken.hasMoreTokens()) {
String i = strToken.nextToken();
int operand;
char operator;
try {
operand = Integer.parseInt(i);
operandStack.push(operand);
} catch (NumberFormatException nfe) {
operator = i.charAt(0);
operatorStack.push(operator);
}
}
// loop until there is only 1 item left in the operandStack, this 1 item left is the result
while(operandStack.size() > 1) {
// some debugging println
System.out.println("Operate\n\tbefore");
System.out.println("\t"+operandStack);
System.out.println("\t"+operatorStack);
// perform the operations on the stack and push the result back onto the operandStack
operandStack.push(operate(operandStack, operatorStack));
System.out.println("\tafter");
System.out.println("\t"+operandStack);
System.out.println("\t"+operatorStack);
}
System.out.println("Result is: " + operandStack.peek());
}
/**
* Performs math operations and returns the result. Pops 2 items off the operandStack and 1 off the operator stack.
* @param operandStack
* @param operatorStack
* @return
*/
private static int operate(Stack<Integer> operandStack, Stack<Character> operatorStack) {
char op = operatorStack.pop();
Integer a = operandStack.pop();
Integer b = operandStack.pop();
switch(op) {
case '-':
return b - a;
case '+':
return a + b;
default:
throw new IllegalStateException("Unknown operator '"+op+"'");
}
}
我離開了operate
方法(以前稱爲sum
)儘可能接近您把它儘可能的東西,但是我覺得你的代碼可以通過簡單地經過2個整數和運營商的改善功能。讓函數改變你的棧不是一件好事,可能會導致混淆的問題。
考慮對你的方法簽名這個代替:
private static int operate(Integer a, Integer b, char operator) {
switch(operator) {
case '-':
return b - a;
case '+':
return a + b;
default:
throw new IllegalStateException("Unknown operator '"+operator+"'");
}
}
,然後從堆棧中彈出,然後把這些的方法。保持你的堆棧在一個地方改變代碼。
operandStack.push(operate(operandStack.pop(), operandStack.pop(), operatorStack.pop()));
什麼是方法'sum'在做什麼? – isnot2bad
@ isnot2bad sum方法計算操作數的總和或乘積。我在sum方法中使用if ... else if語句來計算。例如:if(operator =='+'){operand1 = operandStack.pop(); operand2 = operandStack.pop();結果=操作數2 +操作數1; }。如何編輯代碼以使其一次評估多個表達式? – Jeremy