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?

1
  • Take a look at this question's answers: stackoverflow.com/questions/2559527/… .... Of course the question's code is a bit different and less concise, but the answers should still help you. Commented Sep 15, 2015 at 20:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much! This doesn't completely solve the problem though, seeing as I then get java.lang.NullpointerException: null, in the terminal.
How are you calling roll()? You should be creating a new Die object by using Die die = new Die(6); (or whatever number you want), then you would call die.roll();.
I'd probably also use r.nextInt(n) + 1 otherwise you could get 0, which doesn't make sense for a die.
Added Die die = new Die(); to the contructor, still getting nullpointer
The line Die die = new Die(); won't compile since you do not have a no argument constructor for Die class.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.