我正在尝试实现以下代码,但遇到了静态引用非静态方法的问题。
public class App {
public static void main (String args[]) {
int result = factorial(5);
System.out.println(result);
}
private int factorial(int value) {
if (value == 0)
return 1;
int sum = value * factorial(value-1);
return sum;
}
}
运行上面的代码,出现以下错误:
Error: Cannot make a static reference to the non-static method factorial() from the type App
如果我从 main 方法中删除 static 关键字,则会收到 NullPointerException 错误堆栈:
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
我不太确定如何解决这个问题,感谢任何帮助。
编辑:我在调用阶乘方法时忘记包含参数,现已修复,抱歉。
最佳答案
必须有一个现有的静态main
方法。它会被查找,当您找不到它时,这就是您收到的错误。
您可以通过使 factorial
成为静态方法来解决您的特定问题。
关于java - 空指针异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16207445/