Doing Java course, at UNI atm, and I'm having a bit of trouble with a dice-problem.
I have the following:
public class Die {
public int eyes;
private java.util.Random r;
private int n;
public Die (int n) {
r = new Random();
this.n = n;
}
public void roll() {
eyes = r.nextInt(Die.n);
}
When compiling I get: non-static variable n cannot be referenced from a static context. How would I go about fixing this, whilst having it randomize from a user given value?
n
is not a static variable, so you cannot refer to it in a static manner (Die.n
).Since it is an instance variable in the
Die
class, and you are referring to it in theDie
class, you can just usen
instead ofDie.n
.Remove
and change it to simply
If
n
were declaredstatic
, you could use the both notations, even though the first one would be redundant (because you're from the inside of containing class)