今天用Java写算法的时候,突然明白了,之前再课程设计中出现的错误Cannot make a static reference to the non-static method F(int) from the type lei原因是这个main主方法是静态的,所以在静态方法中不可以直接调用非静态方法。
public class lei {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入数字:");
int data=scanner.nextInt();
System.out.println("结果为:"+f(data));
}
//求阶乘
int f(int n) {
if(n==0)
return 1;
return n*f(n-1);
}
之所以出现这个错误就是因为这个f()是实例方法,当类的字节码被加载到内存时,实例方法不会被分配入口地址,只有该类创建对象时,类中的实例方法才分配入口地址,所以实例方法只能通过对象调用。而类方法是当类加载到内存中,就分配了相应的内存地址,所以类方法不仅可以通过对象调用,也可以用类名调用。
此程序有两种修改方式:第一种是将此方法变为用static修饰的类方法;第二种是创建对象,用对象调用此实例方法。