public class fakultaet1 {
public static long fakultaet(long n) {
if (n<0)
throw new FakultaetNichtDefiniertException(n);
if (n==0)
return 1;
long fakultaet = 1;
while(n>1){
fakultaet *= n; // had a litte mistake here
n--;
}
return fakultaet;
}
public class FakultaetNichtDefiniertException extends RuntimeException{
public FakultaetNichtDefiniertException(long n){
super("Die Fakultät is für den Wert "+ n +" nicht definiert.");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fakultaet(5));
}
}
因此,我希望我的代码计算输入n的阶乘,并且当数字小于0时,它应该引发Exception,但是如果我尝试运行,它将给出此输出。
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type fakultaet1 is accessible. Must qualify the
allocation with an enclosing instance of type fakultaet1 (e.g. x.new A()
where x is an instance of fakultaet1).
at klausur_ws1718.fakultaet1.fakultaet(fakultaet1.java:8)
at klausur_ws1718.fakultaet1.main(fakultaet1.java:29)
我不太了解错误。提前致谢。
最佳答案
您将FakultaetNichtDefiniertException
类定义为fakultaet1
的内部类,这意味着,如果提供封闭的fakultaet1
类的实例,则只能创建该实例的实例。这没有多大意义。
您可以将异常类移出fakultaet1
,或使其成为嵌套类(静态),该嵌套类不需要封闭的实例:
static class FakultaetNichtDefiniertException extends RuntimeException{
public FakultaetNichtDefiniertException(long n){
super("Die Fakultät is für den Wert "+ n +" nicht definiert.");
}
}