Reputation: 51
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));
}
}
So i want my code to calculate the factorial of the input n, and it should throw an Exception when the number is less than 0, but if i try to run it gives me this output.
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)
I do not really understand the Error. Thanks in advance.
Upvotes: 0
Views: 264
Reputation: 51
Your FakultaetNichtDefiniertException class is an inner class of class fakultaet1. You cannot instantiate an object of an inner class if there is no instance of the enclosing class available in the scope. A possible solution is to make the inner class static. Another solution is to define the inner class as a normal class, outside of the enclosing class.
Java - No enclosing instance of type Foo is accessible
Upvotes: 1
Reputation: 393986
You defined the FakultaetNichtDefiniertException
class as an inner class of fakultaet1
, which means you can only create an instance of it if you supply an instance of the enclosing fakultaet1
class. This doesn't make much sense.
You can either move the exception class out of fakultaet1
, or make it a nested class (static), which doesn't require an enclosing instance:
static class FakultaetNichtDefiniertException extends RuntimeException{
public FakultaetNichtDefiniertException(long n){
super("Die Fakultät is für den Wert "+ n +" nicht definiert.");
}
}
Upvotes: 5