【问题标题】:Cannot pass random enum value to function in Java无法将随机枚举值传递给 Java 中的函数
【发布时间】:2021-12-27 20:15:16
【问题描述】:

干杯,我对 java 很陌生,我和我遇到了一个问题 我有三个类,它们都继承了它们之间的东西。开始我有一个 A 类:

public class A{
    private int index;

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

然后我有一个 A 的子类,M 类,里面有一个枚举:

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;
    }   
}

最后是最后一个类 P,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;
    }

}

我想做的是创建例如P 类的 3 个对象,并将每个枚举的值随机传递给它们。我想在主类中创建一个函数,类似于:

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;
    }
  }

我的主要看起来像这样:

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

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

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

但是我收到此错误:Cannot make a static reference to the non-static method 。我可以做些什么来实现我想要的?

【问题讨论】:

    标签: java parameters static parameter-passing


    【解决方案1】:

    错误告诉我们该怎么做:

    不能对非静态方法进行静态引用

    您的主要方法是静态的,从中调用的方法也应该是静态的。所以你的getRandLetter()getRandT() 方法应该是静态的。

    getRandLetter() 应如下所示:

    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;
        }
      }
    

    getRandT() 也应该是静态的。

    【讨论】:

    • 非常感谢您的回复。我有一个问题。我可以在代码的其他地方定义这个函数会更干净吗?假设作为枚举的成员函数?或者这会导致问题吗?再次感谢 =)
    • 这是一种方法,但它会让你陷入静态的蛇坑。这篇文章stackoverflow.com/questions/8117781/… 描述了一个更好的解决方案,它描述了如何通过实例化包含 main() 函数的类的对象来逃避静态陷阱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2015-12-13
    相关资源
    最近更新 更多