Java syntax error on `System.out.println()` method call [closed]

徘徊边缘 提交于 2019-12-08 04:28:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!