This question already has an answer here:
I am getting an error which i don't understand:
Multiple markers at this line - Syntax error on token(s), misplaced construct(s) - Syntax error on tokens, delete these tokens
The following is my code for the class, error occurs in line 8 (marked):
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()
{
}
}
The statement precedence.put("+", 2);
has to be within a method or a block.
For example, you can place it within the constructor
public stringCalculator() {
precedence.put("+", 2);
}
Not related to the problem you have, classes need to start with a capital letter, according to the Java Naming Conventions
precedence.put("+", 2); <=========== This is where the error occurs
this statement is not inside any block , hence it is not permitted.
remove it from here and put it inside any other method or block
Note: this is how java works.
for an extended discussion, please refer to:
precedence.put("+", 2);
The above line is incorrectly placed. You should initialise the Hashtable in constructor.
Statements should be placed in inside constructors/methods/blocks, otherwise Compile time error occurs.
precedence.put("+", 2); <=========== This is where the error occurs
Move that line to constructor/method.
来源:https://stackoverflow.com/questions/20702050/syntax-error-on-tokens