java - 无法为字段设置随机枚举
问题描述
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();
推荐阅读
- mysql - Laravel 应用程序 - SQLSTATE[HY000] [2002] 连接被拒绝
- amazon-web-services - 仅从 s3 存储桶文件夹中获取文件名并使用胶水在文本文件中的另一个存储桶上打印
- python - 如何在 Python 中复制以下条件?
- google-cloud-platform - 在 Dataflow 中创建作业时出错(当前用户不能充当服务帐户)
- python - AutoArima - 为 m 选择正确的值
- azure-devops - Azure Devops 中多个项目的单个或多个部署池
- python - 如何解析带有时区的时间戳?
- c++ - 套接字接受中使用的地址超时
- python - Matplotlib 对多个绘图进行动画处理,并叠加
- r - 在R中将一个单元格拆分为多列