java - 无法为字段设置随机枚举

标签 java class random enumerated-types

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

其中 Location 是一组位置的枚举,例如 {BEDROOM, GARDEN, KITCHEN}.etc。当我创建一个播放器,然后打印出播放器时,randLocation始终为空,我尝试更改构造函数但仍然无济于事。任何帮助都会有用的! 谢谢。

最佳答案

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

this.randLocation=getrandLocation();

关于java - 无法为字段设置随机枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59144137/

相关文章:

java - 使用加载时编织时未编织父类(super class)中的@Transactional

java - 是否也可以在没有 Hibernate 的情况下访问 Hibernate 管理的数据库?

c++ - 在多个源/头文件中使用 c++ 类时的头文件设置

java - android onQuerySubmit() 方法搜索小部件给出错误

Java:原始类型变体的代码结构和类命名 - 最佳实践

c++ - 静态成员函数访问静态私有(private)变量时链接器错误

asp.net-mvc - 在 ASP.NET Core 中生成唯一的随机数

c - 得到错误的随机数总和

r - 创建名称数量不断增加的随机数据框列表

java - 使用 MySQL 的登录/注册 Servlet