1

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;   
        }

2
  • 3
    Perhaps ask() should be static? Otherwise result needs to be initialized to one of the enum constants before you can invoke a method on the instance. Commented Aug 3, 2020 at 0:27
  • Right on, static feels like the right solution here. Commented Aug 3, 2020 at 0:28

4 Answers 4

1

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;   
        }
Sign up to request clarification or add additional context in comments.

Comments

1

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;   
        }

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.