Home > front end >  Cannot pass random enum value to function in Java
Cannot pass random enum value to function in Java

Time:12-28

Cheers, I am pretty new to java and I and I have ran across a problem I have three classes, all inheriting things between them. Starting I have a class A:

public class A{
    private int index;

    public A(int index) {
        System.out.println("Creating an instance of A");
        this.index = index;
    }
}

then I have a sublass of A, class M which has a enum inside as:

public class M extends A{

    public enum Letter {
        A,B,C;
    }
    private Letter letter;

    public M(int index, Letter aLetter) {
        super(index);
        System.out.println("Creating an instance of M");
        this.letter = aLetter;
    }   
}

and finally a last class P , subclass of M:

public class P extends M {
    private T t;

    public enum T{
        o,
        a,
        t
    }

    public P(int index, Letter aLetter, T aT) {
        super(index,aLetter);
        System.out.println("Creating an instance of P");
        this.t = aT;
    }

}

What I want to do is create e.g. 3 objects of the class P, and pass on to them RANDOMLY a value of each of these enums. I thought of creating a function in the main class which would be kind of like:

Letter getRandLetter() {
    Random rand = new Rand();
    int pick = rand.nextInt(M.Letter.values().length);
    if (pick == 0) {
      return Letter.A;
    } else if (pick == 1) {
      return Letter.B;
    } else {
      return Letter.C;
    }
  }

my main looks like this:

int N = 3;
M[] new_m = new M[N]

for(int i = 0; i < N; i  ) {

        new_m[i] = new P(i, getRandLetter(), getRandT());
      }

however I get this error: Cannot make a static reference to the non-static method . What Can I do to achieve what I want?

CodePudding user response:

The error is telling what to do:

Cannot make a static reference to the non-static method

Your main method is static, and the methods called from it should be static as well. So your getRandLetter() and getRandT() methods should be static.

getRandLetter() should look like this:

static Letter getRandLetter() {
    Random rand = new Rand();
    int pick = rand.nextInt(M.Letter.values().length);
    if (pick == 0) {
      return Letter.A;
    } else if (pick == 1) {
      return Letter.B;
    } else {
      return Letter.C;
    }
  }

And getRandT() should be static as well.

  • Related