【问题标题】:Syntax error on tokens [duplicate]令牌上的语法错误[重复]
【发布时间】:2013-12-20 10:56:43
【问题描述】:

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

此行有多个标记 - 令牌上的语法错误,放错了位置 结构体) - 标记的语法错误,删除这些标记

以下是我的类代码,第8行出现错误(标记):

import java.util.*;

public class stringCalculator {
    String operator_array[] = {"+", "-", "/", "*", "(", ")"};
    Queue<Integer> outputQueue = new LinkedList<Integer>();
    Stack <Object> operatorStack = new Stack<Object>();
    Hashtable<String, Integer> precendece = new Hashtable<String, Integer>();
    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()
    {

    }
}

【问题讨论】:

  • 你应该在构造函数中初始化Hashtable。

标签: java dictionary syntax hashmap syntax-error


【解决方案1】:

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

例如,你可以把它放在构造函数中

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

与你遇到的问题无关,类需要以大写字母开头,根据Java Naming Conventions

【讨论】:

  • 完美。非常感谢:)
【解决方案2】:
precedence.put("+", 2); <=========== This is where the error occurs

此语句不在任何块内,因此是不允许的。

从这里删除它并将其放入任何其他方法或块中

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

更多讨论请参考:

Why can't I do assignment outside a method?

【讨论】:

    【解决方案3】:
    precedence.put("+", 2);
    

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

    【讨论】:

      【解决方案4】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-16
        相关资源
        最近更新 更多