令牌语法错误

我收到一个我不明白的错误:

此行的多个标记 – 令牌上的语法错误,错位的构造 – 令牌上的语法错误,删除这些令牌

以下是我的类代码,错误发生在第8行(标记):

import java.util.*; public class stringCalculator { String operator_array[] = {"+", "-", "/", "*", "(", ")"}; Queue outputQueue = new LinkedList(); Stack  operatorStack = new Stack(); Hashtable precendece = new Hashtable(); precedence.put("+", 2); <=========== This is where the error occurs public void printTokenList(String [] expression, int length) { for(int i = 0; i < length; i++){ System.out.println(expression[i]); } } public void checkInput(String [] expression, int length) { System.out.println(expression); for(int i = 0; i < length; i ++){ if(checkIfNumber(expression[i])){ int new_expression = Integer.parseInt(expression[i]); outputQueue.add(new_expression); } else if(expression[i].equals("+") || expression[i].equals("-") || expression[i].equals("/") || expression[i].equals("*")){ for(int j = 0; j < 6; j++){ if(expression[i].equals(operator_array[j])){ operatorStack.push(expression[i]); } } } } } public static boolean checkIfNumber(String expression) { try { double number = Double.parseDouble(expression); } catch(NumberFormatException nfe) { return false; } return true; } public void checkPrecedence() { } } 

语句precedence.put("+", 2); 必须在方法或块内。

例如,您可以将其放在构造函数中

 public stringCalculator() { precedence.put("+", 2); } 

根据Java命名约定 ,与您遇到的问题无关,类需要以大写字母开头

 precedence.put("+", 2); <=========== This is where the error occurs 

此声明不在任何块内,因此不允许。

将其从此处移除并将其放入任何其他方法或块中

注意:这就是java的工作原理。

如需进一步讨论,请参阅:

为什么我不能在方法之外做任务?

 precedence.put("+", 2); 

上面的行放错了。 您应该在构造函数中初始化Hashtable。

语句应放在内部构造函数/方法/块中,否则会发生编译时错误。

 precedence.put("+", 2); <=========== This is where the error occurs 

将该行移动到构造函数/方法。