Languages
[Edit]
EN

Java - get random element from enum

10 points
Created by:
Root-ssh
69560

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

Java - random numbers

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join