Languages
[Edit]
DE

Java - ein zufälliges Element aus enum holen

3 points
Created by:
Nikki
1659

1. Eine zufÀllige AufzÀhlung mit der Random-Klasse generieren

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