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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9763584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:22:57  来源:igfitidea点击:

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

javasyntax-error

提问by Vladislav Bogdanov

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

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

回答by Oliver Charlesworth

You have statements outsideyour method body.

方法主体之外有语句。

回答by jefflunt

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, unlessit'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.

似乎在任何方法之外。您不能只在方法之外运行代码,除非它是变量/常量声明、类声明或其他特殊情况。这就是为什么您会在System.out.println(...)调用中出现语法错误,而在static long start...orlong end...声明中却没有。

回答by Java42

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

回答by KingFeming

You will get Syntax error on token when you have wrote all your java codes in the class itself without defining a method.

当您在类本身中编写所有 java 代码而没有定义方法时,您将在令牌上收到语法错误。

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.

这种方式也能解决问题。