`System.out.println()`方法调用的Java语法错误

时间:2012-03-19 00:23:38

标签: java syntax-error

我很抱歉这个极短的问题,但我甚至不知道为什么会有这个错误:

Syntax error on token "println", = expected after this token

在此代码中:

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.");

4 个答案:

答案 0 :(得分:12)

您的方法正文之外

答案 1 :(得分:4)

你的最后两行:

long end ...
System.out.println...

似乎不在任何方法之内。您不能只在方法之外运行代码,除非它是变量/常量声明,类声明或其他特殊情况。这就是您在System.out.println(...)调用时遇到语法错误的原因,而不是static long start...long end...声明中的语法错误。

答案 2 :(得分:1)

如果您在类中编写了所有java代码而未定义方法,则会在令牌上出现语法错误。

解决这类问题的方法是,只需在类下创建一个方法/主方法,然后在那里进行编码。

这种方式也可以解决问题。

答案 3 :(得分:0)

正如其他人所说,但要修复,请执行以下操作:

变化

long end = System.currentTimeMillis(); 
System.out.println("Execution time was " + (end - start) + " ms."); 

static {
  Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run(){
    long end = System.currentTimeMillis(); 
    System.out.println("Execution time was " + (end - start) + " ms."); 
    }});
}