我正在重建一个堆栈计算器,所以它是递归的。但是,我收到一个错误:
stacks2.java:29: illegal start of expression
public calculate(Stack<String> stack) {
^
stacks2.java:29: ';' expected
public calculate(Stack<String> stack) {
您如何正确地将堆栈传递给方法。
import java.util.*;
public class stacks2 {
public static void main (String []args){
System.out.printf("Enter a math equation in reverse polish notation:\n");
//Create stack of Strings
Stack<String> rpnStack = new Stack<String>();
//Create Scanner
Scanner input = new Scanner(System.in);
//String in = input.next();
while(input != null) {
String in = input.next();
// Tokenize string based on spaces.
StringTokenizer st = new StringTokenizer(in, " ", false);
while (st.hasMoreTokens()) {
rpnStack.push(st.nextToken());
}
//Send stack to Calculation Method
calculate(rpnStack);
}
}
public static void calculate(Stack<String> stack) {
// Base case: stack is empty => Error, or finished
if (!stack.isEmpty())
// throw new StackUnderflowException("Empty Stack");
// Base case: stack has 1 element, which is the answer => finished
if (stack.size(1))
System.out.printf("Finished, Answer: %f\n",stack.peek());
// Recursive case: stack more elements on it.
if (stack.size() > 1){
String temp1 = stack.peek();
stack.pop();
String temp2 = stack.peek();
stack.pop();
String temp3 = stack.peek();
stack.pop();
if (temp3.equals("+")){
float resultant = Float.parseFloat(temp1) + Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
if (temp3.equals("-")){
float resultant = Float.parseFloat(temp1) - Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
else if (temp3.equals("*")){
float resultant = Float.parseFloat(temp1) * Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
else if (temp3.equals("/")){
float resultant = Float.parseFloat(temp1) / Float.parseFloat(temp2);
stack.push(String.valueOf(resultant));
//System.out.println(resultant);
calculate(stack);
}
else{
System.out.printf("Something severely has gone wrong.");
}
}
}
}
代码简要描述:我做了一个堆栈,通过字符串标记器用用户输入填充它。然后我想将它传递给我的计算方法。它应该\应该反复询问用户RPN中的表达式,如果表达式有效,则计算结果,否则宣布错误。为此,我相信我必须计算,如果 RPN 格式错误,则在计算过程中停止。我排在前三根弦上。临时三应该始终是操作员。如果不是,则 RPN 的格式不正确。如果代码为空,则程序抛出下溢异常。当有 1 个元素时,我将其返回以获取答案。我相信我的 if 陈述是正确的。所以是的,我想看看它是否有效,但是现在传递堆栈有点阻碍我。