在做包的练习中,当编译"text.java"文件时,报错了...
不知错在哪? (求5!)
程序如下:
package mypackage;
public class factorial{
long s=1L;
public void factorial(long n){
if (n<0)
System.out.println("请输入正数!");
else
inspect(n);
}
final long inspect(long n){
if (n==0) return 1;
return s=s*inspect(n-1);
}
public void printS(){
System.out.println("5!="+s);
}
}
package mypackage1;
import mypackage.factorial;
public class text{
public static void main(String [] args){
factorial f=new factorial(5);
f.printS();
}
}
请大家帮我看一下!
----------------解决方案--------------------------------------------------------
因为factorial没有构造器~~所以只能用默认构造器~default factorial()对于不同包是不可见的!~所以text.java出错!~
----------------解决方案--------------------------------------------------------
public class Factorial{ //最好遵守类名首字母大写规则
long s;
public Factorial(long n){ //构造方法无任何返回类型,比较特殊.
if(n<0)
System.out.println(\"Please input a positive integer\");
else
s=inspect(n); //在此处对实例变量进行赋值
}
final long inspect(long n){
if(n==0)
return 1;
else
return n*inspect(n-1);
}
public void printS(){
System.out.println(\"5!=\"+s);
}
}
public class Text{
public static void main(String[] args){
Factorial f=new Factorial(5);
f.printS();
}
}
----------------解决方案--------------------------------------------------------
呵呵,楼上写的不错~
----------------解决方案--------------------------------------------------------
2楼的,"因为factorial没有构造器" 怎么做啊?
3楼的,,,我这里主要是想做一个关于 包 的练习!
----------------解决方案--------------------------------------------------------
问题解决!
3楼说得对,构造函数没返回类型.
把包放进去就好了!
----------------解决方案--------------------------------------------------------
package mypackage;
public class factorial{
long s=1L;
public factorial(long n){
if (n<0)
System.out.println("请输入正数!");
else
inspect(n);
}
final long inspect(long n){
if (n==0) return 1;
return s=s*inspect(n-1);
}
public void printS(){
System.out.println("5!="+s);
}
}
package mypackage1;
import mypackage.factorial;
public class text{
public static void main(String [] args){
factorial f=new factorial(5);
f.printS();
}
}
----------------解决方案--------------------------------------------------------