0

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?

the
  • 21,007
  • 11
  • 68
  • 101
  • Take a look at this question's answers: http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context .... Of course the question's code is a bit different and less concise, but the answers should still help you. – rodamn Sep 15 '15 at 20:56

2 Answers2

3

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 the Die class, you can just use n instead of Die.n.

Evan LaHurd
  • 977
  • 2
  • 14
  • 27
1

Remove

Die.n

and change it to simply

n

If n were declared static, you could use the both notations, even though the first one would be redundant (because you're from the inside of containing class)

Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48