Languages
[Edit]
EN

Java - get random element from enum

10 points
Created by:
Root-ssh
177980

1. Generate random enum with Random class

import java.util.Random;

public class JavaEnumGetRandomElement {

    enum ColorEnum {
        GREEN,
        BLUE,
        RED,
        YELLOW;

        public static ColorEnum generateRandomColor() {
            ColorEnum[] values = ColorEnum.values();
            int length = values.length;
            int randIndex = new Random().nextInt(length);
            return values[randIndex];
        }
    }

    public static void main(String[] args) {
        System.out.println(ColorEnum.generateRandomColor()); // RED
        System.out.println(ColorEnum.generateRandomColor()); // YELLOW
        System.out.println(ColorEnum.generateRandomColor()); // GREEN
    }
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join