英文:
Determine the enum value using a value
问题
我卡在一个看似简单的问题上。
假设我有以下枚举:
enum CARDS {
JOKER(1),
JACK(2),
QUEEN(3),
KING(4),
ACE(5)
;
private final int cardNumber;
CARDS(int cardNumber) {
this.cardNumber = cardNumber;
}
}
我想找到一种方法,可以使用从另一个类随机生成的整数来确定枚举(JOKER、JACK、QUEEN、KING、ACE)的值。这是否可能,是否是良好的实践?
例如:
我有一个整数,比如3。
我想将这个整数与枚举分配的常量值匹配,这种情况下我的整数3将与queen配对。
英文:
I am stuck on what feels like a seemingly simple question.
Say I have the following enum:
enum CARDS {
JOKER(1),
JACK(2),
QUEEN(3),
KING(4),
ACE(5)
;
private final int cardNumber;
CARDS(int cardNumber) {
this.cardNumber = cardNumber;
}
}
I would like to find a way to determine the value of an enum (JOKER, JACK, QUEEN, KING, ACE) using an integer that is randomly generated from a separate class. Would this be possible, and is this good practice?
For example:
I have an integer, say, 3.
I would like to match the integer to the constant value assigned to the enum, in this case my integer 3 would result in being paired to queen.
答案1
得分: 3
这就是简单的方法:
```java
int integer = 3;
CARDS card = CARDS.values()[integer - 1];
注意:这样可以工作,因为QUEEN的序号是2(从零开始)。
使用CARDS.valueOf(String)
将枚举名称转换为CARDS成员。
至于良好的实践,我建议设计一个利用序号进行排序和随机选择的方式,如果需要等级或强度,可以将它们作为单独的属性(就像你做的那样)。
你可以这样随机选择一个成员:
CARDS[] deck = CARDS.values();
Random random = new Random();
CARDS card = deck[random.nextInt(deck.length)];
而不依赖于任何特定的序号值。
<details>
<summary>英文:</summary>
It's as simple as:
```java
int integer = 3;
CARDS card = CARDS.values()[integer - 1];
Note: This works because QUEEN's ordinal is 2 (zero-based).
Use CARDS.valueOf(String)
to convert an enum name to CARDS member.
As far as good practice, I suggest a design that takes advantage of the ordinal for ordering and random selection and if you need rank or strength, make those separate attributes (as you did).
You might select a random member with:
CARDS[] deck = CARDS.values();
Random random = new Random();
CARDS card = deck[random.nextInt(deck.length)];
without relying on any specific ordinal value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论