Languages
[Edit]
EN

Java - get random element from enum

10 points
Created by:
Root-ssh
6253

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

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Java - random numbers

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍