问题
I'm sorry for the extremely short question, but i don't even know why i have this error:
Syntax error on token "println", = expected after this token
In this code:
static long start = System.currentTimeMillis();
public void testSort5() {
Random random = new Random();
int number;
int[] arr = new int[1000];
for (int counter = 1; counter < 1000; counter++) {
number = 1 + random.nextInt(1000);
arr[counter] = number;
}
int[] actual = MergeSort.sort(arr);
}
long end = System.currentTimeMillis();
System.out.println("Execution time was " + (end - start) + " ms.");
回答1:
You have statements outside your method body.
回答2:
Your last two lines:
long end ...
System.out.println...
Appear to be outside of any method. You can't just run code outside of a method, unless it's a variable/constant declaration, a class declaration, or other special situations. This is why you get the syntax error on the System.out.println(...)
call, but not on the static long start...
or long end...
declarations.
回答3:
As the others said, but to fix, do the following:
change
long end = System.currentTimeMillis();
System.out.println("Execution time was " + (end - start) + " ms.");
to
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run(){
long end = System.currentTimeMillis();
System.out.println("Execution time was " + (end - start) + " ms.");
}});
}
回答4:
You will get Syntax error on token when you have wrote all your java codes in the class itself without defining a method.
Solution for this type of issue is, simply create a method/ main method under the class and then code there..
This way will resolve the problem too.
来源:https://stackoverflow.com/questions/9763584/java-syntax-error-on-system-out-println-method-call