我正在尝试以下代码并使用JDK 1.8.0_66进行编译。我的代码似乎在语法上是正确的,我错过了什么吗?
interface Executable {
void execute();
}
class Runner {
public void run(Executable e) {
System.out.println("Executing code block!");
e.execute();
}
}
public class HelloWorld {
public static void main(String[] args) {
Runner runner = new Runner();
runner.run(new Executable() {
public void execute() {
System.out.println("IN ANONYMOUS CLASS EXECUTE");
}
});
}
runner.run(() -> System.out.println());
}
抛出以下编译错误:
App.java:25: error: <identifier> expected
runner.run(() -> System.out.println());
^
App.java:25: error: illegal start of type
runner.run(() -> System.out.println());
^
App.java:25: error: ';' expected
runner.run(() -> System.out.println());
答案 0 :(得分:4)
您的语句位于块之外,其中定义了runnner
变量。应该是这样的:
public static void main(String[] args) {
Runner runner = new Runner();
runner.run(new Executable() {
public void execute() {
System.out.println("IN ANONYMOUS CLASS EXECUTE");
}
});
runner.run(() -> System.out.println());
}
答案 1 :(得分:3)
这行代码需要在代码块中。因此,您需要将其移动到main
方法的主体中:
更改
} // end of main
runner.run(() -> System.out.println());
到
runner.run(() -> System.out.println());
} // end of main
答案 2 :(得分:-1)
runner.run(() - &gt; System.out.println()); - 是主要方法之外。将代码放在main方法中,它将完美地运行。