【问题标题】:Unable to set a random enum to a field无法为字段设置随机枚举
【发布时间】:2019-12-03 01:51:19
【问题描述】:
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 始终为空,我尝试更改构造函数但仍然无济于事。任何帮助都会很有用! 谢谢。

【问题讨论】:

  • 你没有在任何地方设置randLocation。我认为你的意图是做this.randLocation = getrandLocation()
  • 您的 ctor 应致电 getrandLocation()。尽管该函数应该创建一个新位置而不是仅仅返回randLocation,这似乎很奇怪。也许对此有不同的功能:public void randomizeLocation() {...}

标签: java class random enumerated-types


【解决方案1】:

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

this.randLocation=getrandLocation();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多