我正在重建一個堆棧計算器,以便它是遞歸的。然而,我得到一個錯誤:如何將堆棧傳遞到方法
stacks2.java:29: illegal start of expression
public calculate(Stack<String> stack) {
^
stacks2.java:29: ';' expected
public calculate(Stack<String> stack) {
你是如何supoosed傳遞一個方法正確的方法。
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格式不正確。如果代碼是空的,那麼程序會拋出一個下溢異常。當有一個元素時,我將它返回給答案。我相信我的陳述是正確的。所以是的,我想看看它是否有效,但是通過堆棧有點阻礙我。
是啊,這太! –
哦,男孩看起來像很多錯誤:X。感謝 – user1093111
@ user1093111。你應該通過'調試器'傳遞你的代碼。但首先要通過編譯器來清除編譯器錯誤。他們會爲您提供代碼中的所有問題。 –