如何从枚举生成随机值并将其放入数组中?
我得到了一个充满“项目”的枚举,我想生成一个枚举的随机项目,然后将其放入我的库存中,我是用一个数组制成的。阵列只有10个int的空间。
public class InventoryEnums {
public static void main (String[] args){
int[] inventar = new int[9] // int array mit 10 Plätzen
enum items {
KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ
}
I got an enum which is filled with "items" and I want to generate one random item of the enum and put it into my inventory, which I made out of an array. The array only has room for 10 ints.
public class InventoryEnums {
public static void main (String[] args){
int[] inventar = new int[9] // int array mit 10 Plätzen
enum items {
KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
枚举应在单数中命名,并应从大写字母开始。
我建议您努力设计一个比“项目”更具描述性的名称。
通过调用
values
来获取所有枚举对象的数组。生成一个随机数。将该数字用作所有项目数组中的索引。
或者,也许您打算随机排序(洗牌)枚举的所有元素。如果是这样,请制作由数组支持的
list
。调用collections.shuffle
。对列表进行的更改也会影响背景阵列。所以阵列被洗了。更简单地:
请参阅此代码在iDeone.com 中实时运行。
An enum should be named in the singular, and should start with an uppercase letter.
And I suggest you work at devising a more descriptive name than “Item”.
Get an array of all the enum objects by calling
values
.Generate a random number. Use that number as the index into your array of all items.
Or perhaps you meant to randomly sort (shuffle) all the elements of the enum. If so, make a
List
backed by the array. CallCollections.shuffle
. Changes made to the list also affect the backing array. So the array is shuffled.More briefly:
See this code run live at Ideone.com.
您可以获得一个随机整数值,该值在范围0到array.length。然后
,您可以获取使用您生成的随机值的
enum
,然后在循环中使用它来填充数组。
You can get a random integer value that is in the range 0 to array.length as
Then you can get the
enum
for the random value generated usingYou then use this in a loop to fill the array.
这不是你想要的吗?
Isn't this what you want?
还有另一种方法:
There is another way: