Using method from enum class

huangapple go评论80阅读模式
英文:

Using method from enum class

问题

我是JAVA的新手,我在使用枚举类时遇到了问题。我有一个名为Answers的枚举类型的类,它具有返回Answers枚举常量的方法:

import java.util.Random;
enum Answers {
    NO, YES;
    Random rand = new Random();
    Answers ask() {
        int prob = (int) (100 * rand.nextDouble());
            
        if (prob > 50)
            return Answers.YES;
        else
            return Answers.NO;
    }
}

然而,当尝试使用该方法打印结果时,我得到了错误消息:变量result可能未被初始化

public static void main(String[] args) {
    Answers result;
    switch (result.ask()) {
        case NO:
            System.out.println("NO");
            break;
        case YES:
            System.out.println("YES");
            break;   
    }
}
英文:

I am newbie in JAVA and I am having trouble with enumeration classes. I have a class of type enum named Answers that possesses the method that returns an Answers enumeration constant:

import java.util.Random;
enum Answers {
    NO,YES;
    Random rand = new Random();
    Answers ask(){
        int prob = (int) (100*rand.nextDouble());
            
        if(prob > 50)
            return Answers.YES;
        else
            return Answers.NO;
    }
}

Nevertheless when trying to print a result using the method I get the error: variable result not might been initialized :

public static void main(String[] args) {
        Answers result;
        switch(result.ask()){
            case NO:
                System.out.println("NO");
                break;
            case YES:
                System.out.println("YES");
                break;   
        }

答案1

得分: 1

You need to initialize the variable result like so:

要初始化变量result,可以这样做:

Answers result = Answers.YES

然后你可以访问对象的方法

然后,你可以访问对象的方法

So your logic doesn't make sense to put it in the enum, Instead, you can have the enum for yes or no and put the logic to generate random answers in a static method

所以,把这个逻辑放在枚举中是没有意义的,相反,你可以在一个静态方法中生成随机答案的逻辑

enum Answers {
NO, YES;
Random rand = new Random();
static Answers ask() {
int prob = (int) (100 * rand.nextDouble());

    if (prob > 50)
        return Answers.YES;
    else
        return Answers.NO;
}

}

Then use it as following

然后按以下方式使用它

public static void main(String[] args) {

switch (Answers.ask()) {
    case NO:
        System.out.println("NO");
        break;
    case YES:
        System.out.println("YES");
        break;
}

}

英文:

You need to initialize the variable result like so :

Answers result = Answers.YES

Then you can access the methods of the object

So your logic doesn't make sense to put it in the enum, Instead, you can have the enum for yes or no and put the logic to generate random answers in a static method

enum Answers {
    NO,YES;
    Random rand = new Random();
    static Answers ask(){
        int prob = (int) (100*rand.nextDouble());
            
        if(prob > 50)
            return Answers.YES;
        else
            return Answers.NO;
    }
}

Then use it as following

public static void main(String[] args) {
        
        switch(Answers.ask()){
            case NO:
                System.out.println("NO");
                break;
            case YES:
                System.out.println("YES");
                break;   
        }

答案2

得分: 1

这个错误告诉你变量可能没有被初始化,你正在将变量result视为Answers的一个实例,如果你想在调用ask()方法时返回Answers的一个实例,你可能应该使用一个静态方法,像这样:

static Answers ask(){
    Random rand = new Random();
    int prob = (int) (100*rand.nextDouble());
        
    if(prob > 50)
        return Answers.YES;
    else
        return Answers.NO;
}

然后你可以像这样调用那个方法:

Answers.ask()

或者将其保存在一个变量中:

public static void main(String[] args) {
    Answers result = Answers.ask();
    switch(result){
        case NO:
            System.out.println("NO");
            break;
        case YES:
            System.out.println("YES");
            break;   
    }
}
英文:

This error is telling you that the variable might not be initialized, you are treating the variable result as an instance of Answers, if you want to return an instance of Answers when calling the ask() method, you should probably use a static method like this.

    static Answers ask(){
        Random rand = new Random();
        int prob = (int) (100*rand.nextDouble());
            
        if(prob > 50)
            return Answers.YES;
        else
            return Answers.NO;
    }

And then you can call that method like this.

Answers.ask()

or

Saving it in a variable

       public static void main(String[] args) {
        Answers result = Answers.ask();
        switch(result){
            case NO:
                System.out.println("NO");
                break;
            case YES:
                System.out.println("YES");
                break;   
        }

答案3

得分: 1

You did not initialize result here, so it makes sense that it doesn't compile.
这里你没有初始化result,所以它不编译是有道理的。
The problem is what is the value of result in your example when you're calling result.ask()?
问题是在你调用result.ask()时,示例中的result的值是多少?
You probably don't want to assign the result to a variable and could just make ask() a static method.
你可能不想将结果分配给一个变量,可以将ask()方法设为静态方法。

英文:

You did not initialize result here, so it makes sense that it doesn't compile.
The problem is what is the value of result in your example when you're calling result.ask()?

You probably don't want to assign the result to a variable and could just make ask() a static method.

答案4

得分: 1

static

请注意,NOYES 是您的 Answer 类的实例。 (顺便说一下,枚举最好用单数形式来命名。)因此,您的 ask 方法应该是 static,而不是常规实例方法。

实际上,我不会将您的 ask 方法放在枚举内部。枚举提供值和数据,但通常不应知道如何使用它,例如随机选择。但我不会深究这个问题。

ThreadLocalRandom

关于 Random 类,我建议改用 ThreadLocalRandom。这可以确保线程安全的代码。您可能不需要线程安全性,但使用 ThreadLocalRandom 没有任何坏处。另一个好处是 ThreadLocalRandom 不会重复创建新的 Random 对象。更重要的是,ThreadLocalRandom 具有方便的方法,比如 nextBoolean,而不需要执行您之前做的数学运算。

调用 ThreadLocalRandom.current() 来获取为该线程建立的随机值生成器。如果尚未建立,将启动一个生成器。

在您的情况下,只需要在 NOYES 值之间选择两个值的范围。因此,调用 ThreadLocalRandom.current().nextBoolean() 来生成一个 truefalse 的值。

三元语句

if 语句不同,这种情况适合使用三元语句。三元语句的紧凑语法如下:

someTestEvaluatingToTrueOrFalse ? thisValueReturnedIfTrue : thisValueReturnedIfFalse

顺便说一下,我将您的方法名称从 ask 更改为 random,以更好地传达它实际的功能。

示例代码

将所有这些内容组合在一起,我们得到以下代码。

enum Answer
{
    NO, YES;

    static Answer random() 
    {
        return ThreadLocalRandom.current().nextBoolean() ? YES : NO;
    }
}

用法:

Answer answer = Answer.random();

IdeOne.com 上运行此代码

英文:

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.

huangapple
  • 本文由 发表于 2020年8月3日 08:23:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63222232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定