Tóm Tắt
tl;dr
static Answer random() { return ThreadLocalRandom.current().nextBoolean() ? YES : NO ; }
static
Be aware that NO
and YES
are the instances of your class Answer
. (By the way, an enum is better named in singular.) So rather than a regular instance method, your ask
method should be static
.
Actually, I would not put your ask
method inside your enum. An enum provides values and data, but should generally not be aware of how it is being used such as randomly selected. But I’ll not dwell on that.
ThreadLocalRandom
Regarding the Random
class, I recommend using instead ThreadLocalRandom
. This makes for thread-safe code. You may not need bread-safety, but there is no downside to using ThreadLocalRandom
. Another benefit to ThreadLocalRandom
is nat launching a new Random
object repeatedly. Best of all, ThreadLocalRandom
has convenient methods such as nextBoolean
without any of the math you were doing.
Call ThreadLocalRandom.current()
to get the random value generator established for this thread. If not yet established, a generator is started.
Your situation needs only a range of two values to choose between your NO
and YES
values. So call ThreadLocalRandom.current().nextBoolean()
to generate a true
or false
value.
Ternary statement
Rather than an if
statement, this situation is a good place for a ternary statement. The compact syntax of a ternary works like this:
someTestEvaluatingToTrueOrFalse ? thisValueReturnedIfTrue : thisValueReturnedIfFalse
By the way, I changed your method name from ask
to random
to better communicate what it actually does.
Example code
Putting that all together, we have the following code.
enum Answer
{
NO , YES ;
static Answer random()
{
return ThreadLocalRandom.current().nextBoolean() ? YES : NO ;
}
}
Usage:
Answer answer = Answer.random() ;
See this code run live at IdeOne.com.