Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法将随机枚举设置为字段_Java_Class_Random_Enumerated Types - Fatal编程技术网

Java 无法将随机枚举设置为字段

Java 无法将随机枚举设置为字段,java,class,random,enumerated-types,Java,Class,Random,Enumerated Types,其中Location是一组枚举的位置,如{卧室、花园、厨房}等。当我创建一个播放器,然后打印出播放器时,randLocation总是空的,我尝试过修改构造函数,但仍然没有用。任何帮助都是有用的! 谢谢。在构造函数中使用以下行: public class Player { public String name; public boolean active; public boolean seeker; public Location randLocation;

其中Location是一组枚举的位置,如{卧室、花园、厨房}等。当我创建一个播放器,然后打印出播放器时,randLocation总是空的,我尝试过修改构造函数,但仍然没有用。任何帮助都是有用的!
谢谢。

在构造函数中使用以下行:

public class Player {

    public String name;
    public boolean active;
    public boolean seeker;
    public Location randLocation;

    public Player(String name, boolean seeker) {
        this.name = name;
        this.seeker = seeker;
        //this.active= true;
        //this.randLocation=randLocation;
    }

    public String getName() {
        return name;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public boolean isSeeker() {
        return seeker;
    }

    public Location getrandLocation() {
        Random random = new Random();
        randLocation = (Location.values()[random.nextInt(Location.values().length)]);
        System.out.println(randLocation);
        return randLocation;
    }

    public void setRandLocation(Location randLocation) {
        this.randLocation = randLocation;
    }

    @Override
    public String toString() {
        return "Player [name=" + name + ", active=" + active + ", seeker=" + seeker + ", randLocation=" + randLocation
                + "]";
    }

    public static void main(String[] args) {
        Player p1 = new Player("p1", false);
        System.out.println(p1);
    }
}

您没有在任何地方设置
randLocation
。我认为您的意图是执行
this.randLocation=getrandLocation()
您的ctor应该调用
getrandLocation()
。尽管该函数应该创建一个新位置而不是仅仅返回
randLocation
似乎有些奇怪。可能对此有不同的函数:
public void randomizeLocation(){…}
this.randLocation=getrandLocation();