在Java的主方法中有一个方法在语法上正确吗?例如
class Blastoff {
public static void main(String[] args) {
//countdown method inside main
public static void countdown(int n) {
if (n == 0) {
System.out.println("Blastoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}
}发布于 2013-02-23 20:30:32
不,不是直接;但是,方法可以包含本地内部类,当然,内部类可以包含方法。This StackOverflow question给出了这方面的一些例子。
但是,在您的示例中,您可能只想从countdown内部调用main;实际上并不需要整个定义在main中。例如:
class Blastoff {
public static void main(String[] args) {
countdown(Integer.parseInt(args[0]));
}
private static void countdown(int n) {
if (n == 0) {
System.out.println("Blastoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}(请注意,我已经将countdown声明为private,因此只能在Blastoff类中调用它,我假设这是您的意图?)
https://stackoverflow.com/questions/15045272
复制相似问题